import os
import csv
from PySide import QtGui, QtCore


class SelectorDialog(QtGui.QDialog):
    def __init__(self, csv_path, title, parent=None):
        super(SelectorDialog, self).__init__(parent)
        self.setWindowTitle(title)
        self.csv_path = csv_path
        self.data = []
        self.brand_filter = ""
        self.model_filter = ""

        # Cargar datos del CSV
        self.load_csv_data()

        # Crear widgets
        self.create_widgets()
        self.create_layout()
        self.create_connections()

    def load_csv_data(self):
        """Carga los datos desde el archivo CSV"""
        if os.path.exists(self.csv_path):
            with open(self.csv_path, 'r') as f:
                reader = csv.DictReader(f, delimiter=';')
                self.data = [row for row in reader]

    def get_unique_brands(self):
        """Obtiene marcas únicas"""
        return list(set(row['Marca'] for row in self.data))

    def get_models_by_brand(self, brand):
        """Filtra modelos por marca"""
        return [row['Modelo'] for row in self.data if row['Marca'] == brand]

    def create_widgets(self):
        self.lbl_brand = QtGui.QLabel("Marca:")
        self.cb_brand = QtGui.QComboBox()
        self.cb_brand.addItems(self.get_unique_brands())

        self.lbl_model = QtGui.QLabel("Modelo:")
        self.cb_model = QtGui.QComboBox()
        self.update_model_combo()

        self.btn_accept = QtGui.QPushButton("Aceptar")
        self.btn_cancel = QtGui.QPushButton("Cancelar")

    def create_layout(self):
        layout = QtGui.QVBoxLayout()
        form_layout = QtGui.QFormLayout()
        form_layout.addRow(self.lbl_brand, self.cb_brand)
        form_layout.addRow(self.lbl_model, self.cb_model)

        button_layout = QtGui.QHBoxLayout()
        button_layout.addWidget(self.btn_accept)
        button_layout.addWidget(self.btn_cancel)

        layout.addLayout(form_layout)
        layout.addLayout(button_layout)
        self.setLayout(layout)

    def create_connections(self):
        self.cb_brand.currentIndexChanged.connect(self.update_model_combo)
        self.btn_accept.clicked.connect(self.accept)
        self.btn_cancel.clicked.connect(self.reject)

    def update_model_combo(self):
        brand = self.cb_brand.currentText()
        models = self.get_models_by_brand(brand)
        self.cb_model.clear()
        self.cb_model.addItems(models)

    def get_selected_item(self):
        brand = self.cb_brand.currentText()
        model = self.cb_model.currentText()
        for row in self.data:
            if row['Marca'] == brand and row['Modelo'] == model:
                return row
        return None


def select_modulo():
    csv_path = "/ruta/a/tu/databases/modulos.csv"  # Ajusta esta ruta
    dialog = SelectorDialog(csv_path, "Seleccionar Módulo")
    if dialog.exec_():
        selected = dialog.get_selected_item()
        print("Módulo seleccionado:", selected)  # Aquí puedes agregar la lógica de importación


def select_inversor():
    csv_path = "/ruta/a/tu/databases/inversores.csv"  # Ajusta esta ruta
    dialog = SelectorDialog(csv_path, "Seleccionar Inversor")
    if dialog.exec_():
        selected = dialog.get_selected_item()
        print("Inversor seleccionado:", selected)  # Aquí puedes agregar la lógica de importación


# Crear una barra de herramientas para acceder fácilmente
toolbar = QtGui.QToolBar()
select_modulo_action = QtGui.QAction("Seleccionar Módulo", toolbar)
select_modulo_action.triggered.connect(select_modulo)
toolbar.addAction(select_modulo_action)

select_inversor_action = QtGui.QAction("Seleccionar Inversor", toolbar)
select_inversor_action.triggered.connect(select_inversor)
toolbar.addAction(select_inversor_action)

# Agregar la barra de herramientas a FreeCAD
Gui.addToolBar(toolbar)