from pathlib import Path

from qgis.core import NULL, Qgis, QgsProviderConnectionException, QgsProviderRegistry
from qgis.PyQt import uic
from qgis.PyQt.QtWidgets import QWidget

from plui_versionning.gui.dlg_create_thematique import CreateThematiqueDialog
from plui_versionning.gui.dlg_prepare_procedure import PrepareProcedureDialog
from plui_versionning.toolbelt import PlgLogger, PlgOptionsManager


class ProcedureWidget(QWidget):
    def __init__(self, parent: QWidget = None):
        """
        QWidget Procédure

        Args:
            parent: parent QWidget
        """
        super().__init__(parent)
        self.parent = parent
        self.log = PlgLogger().log
        self.plg_settings = PlgOptionsManager()

        # DB connection
        self.db_connection_uri = self.plg_settings.get_plg_settings().db_connection_uri
        self.db_schema_name = self.plg_settings.get_plg_settings().db_schema_name

        uic.loadUi(Path(__file__).parent / f"{Path(__file__).stem}.ui", self)

        self.id_procedure = None
        self.wdg_procedure_details.setVisible(False)
        self.btn_creer_thematique.setVisible(False)
        self.btn_importer_thematique.setVisible(False)
        self.btn_terminer_procedure.setVisible(False)
        self.fill_procedure_combobox()
        self.cb_procedure.currentIndexChanged.connect(self.procedure_changed)
        self.btn_creer_thematique.clicked.connect(self.create_thematique)
        self.btn_terminer_procedure.clicked.connect(self.prepare_procedure)

    def fill_procedure_combobox(self):
        """Fill combobox with procedures"""
        # Clear combobox
        self.cb_procedure.clear()

        sql = """
            select id, intitule, procedure_plui, code_proc, num_proc , num_phase from "{}".v_pluiv_procedures
            order by id
        """.format(
            self.db_schema_name
        )
        # where "{}".func_verifier_statut_procedure(code_proc, num_proc, num_phase) = true
        md = QgsProviderRegistry.instance().providerMetadata("postgres")
        conn = md.createConnection(self.db_connection_uri, {})
        try:
            result = conn.executeSql(sql)
            for proc in result:
                self.cb_procedure.addItem(proc[2], proc[0])
        except QgsProviderConnectionException as e:
            self.log(message=e, log_level=Qgis.Critical, push=True)

        self.cb_procedure.setCurrentIndex(-1)

    def procedure_changed(self, index):
        """Event when user change procedure in combobox."""
        self.id_procedure = self.cb_procedure.itemData(index)
        self.wdg_procedure_details.setVisible(self.id_procedure is not None)
        self.btn_creer_thematique.setVisible(self.id_procedure is not None)
        self.btn_importer_thematique.setVisible(self.id_procedure is not None)
        self.btn_terminer_procedure.setVisible(self.id_procedure is not None)
        if self.id_procedure is None:
            return
        self.btn_creer_thematique.setEnabled(not self.is_procedure_terminated())
        self.wdg_procedure_details.set_procedure(self.id_procedure)
        self.parent.set_procedure(self.id_procedure)

    def create_thematique(self):
        """Shows dialog to create new thematique in current procedure"""
        dlg_create_thematique = CreateThematiqueDialog(
            id_procedure=self.id_procedure, parent=self
        )
        dlg_create_thematique.exec_()

    def prepare_procedure(self):
        """Shows dialog to prepare end of current procedure"""
        dlg_prepare_proc = PrepareProcedureDialog(
            id_procedure=self.id_procedure, parent=self
        )
        dlg_prepare_proc.exec_()

    def is_procedure_terminated(self) -> bool:
        """Return true if procedure has datefin_proc != NULL"""
        query = 'select datefin_proc from "{}".v_pluiv_procedures where id = {}'.format(
            self.db_schema_name, self.id_procedure
        )
        md = QgsProviderRegistry.instance().providerMetadata("postgres")
        conn = md.createConnection(self.db_connection_uri, {})
        try:
            result = conn.executeSql(query)
            return result[0][0] != NULL
        except QgsProviderConnectionException as e:
            self.log(message=e, log_level=Qgis.Critical, push=True)
        return False
