from pathlib import Path

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

from plui_versionning.core.utils import catch_postgres_exception
from plui_versionning.toolbelt import PlgLogger, PlgOptionsManager

CLORE_PROCEDURE = 0
INIT_PHASE = 1


class TerminateProcedureDialog(QDialog):
    def __init__(self, id_procedure: int, parent: QWidget = None, *args, **kwds):
        """
        QDialog Terminer une procédure
        """
        super().__init__(parent, *args, **kwds)
        self.log = PlgLogger().log

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

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

        self.id_procedure = id_procedure  # Procédure courante
        self.procedure_plui = self.get_procedure()
        self.lbl_procedure_value.setText(self.procedure_plui)
        self.btn_grp_action.setId(self.radio_btn_clore, CLORE_PROCEDURE)
        self.btn_grp_action.setId(self.radio_btn_init_phase, INIT_PHASE)

    def accept(self):
        query = """
        select \"{}\".qgis_terminer_procedure({}, {})
        """.format(
            self.db_schema_name,
            self.id_procedure,
            self.btn_grp_action.checkedId() == INIT_PHASE,
        )
        md = QgsProviderRegistry.instance().providerMetadata("postgres")
        conn = md.createConnection(self.db_connection_uri, {})
        try:
            conn.executeSql(query)
            msg = f"La procédure {self.procedure_plui} a été gelée. Ses objets associés ne sont plus éditables."
            self.log(
                message=msg,
                log_level=Qgis.Success,
                push=True,
            )
            QMessageBox().information(
                self,
                f"Procédure {self.procedure_plui} gelée",
                msg,
            )
            self.close()
        except QgsProviderConnectionException as e:
            self.log(
                message=catch_postgres_exception(str(e)),
                log_level=Qgis.Critical,
                push=True,
            )

    def get_procedure(self) -> str:
        """Return procedure_plui in pluiv_procedures table regarding id"""
        query = (
            'select procedure_plui 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]
        except QgsProviderConnectionException as e:
            self.log(message=e, log_level=Qgis.Critical, push=True)
        return None
