from pathlib import Path

from qgis.core import Qgis, QgsProviderConnectionException, QgsProviderRegistry
from qgis.PyQt import uic
from qgis.PyQt.QtCore import pyqtSignal
from qgis.PyQt.QtWidgets import QListWidgetItem, QWidget

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


class CreateThematiqueWidget(QWidget):
    # Signal pour rafraichir les catégories disponibles dans le tableau
    refreshCategories = pyqtSignal()

    def __init__(self, parent: QWidget = None):
        """
        QWidget Créer une thématique

        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  # Procédure courante dans laquelle créer la thématique
        self.classe = None
        self.categorie = None
        self.btn_creer_thematique.setEnabled(False)
        self.edit_intitule.textChanged.connect(self.enable_button)
        self.list_sous_types.itemSelectionChanged.connect(self.enable_button)
        self.btn_creer_thematique.clicked.connect(self.create_thematique)

    def enable_button(self):
        """Enable/Disable button"""
        (
            self.btn_creer_thematique.setEnabled(True)
            if (
                len(self.list_sous_types.selectedItems()) > 0
                and self.edit_intitule.text()
            )
            else self.btn_creer_thematique.setEnabled(False)
        )

    def set_classe_entite(self, classe: ClasseEntite):
        self.classe = classe
        self.lbl_classe_entite_value.setText(self.classe["name"])

    def set_procedure(self, id_procedure: int):
        self.id_procedure = id_procedure

    def set_categorie(self, categorie: str):
        self.categorie = categorie
        self.lbl_categorie_value.setText(f"{self.classe['thematique']}{self.categorie}")
        self.load_sous_types()

    def get_list_sous_types(self):
        query = """
            select stype from {}.v_pluiv_categories_disponibles
            where classe_entite = '{}' and code_cnig = '{}'
        """.format(
            self.db_schema_name, self.classe["code"], self.categorie
        )
        md = QgsProviderRegistry.instance().providerMetadata("postgres")
        conn = md.createConnection(self.db_connection_uri, {})
        try:
            result = conn.executeSql(query)
            if result:
                return result
        except QgsProviderConnectionException as e:
            self.log(message=e, log_level=Qgis.Critical, push=True)

    def load_sous_types(self):
        self.list_sous_types.clear()
        sous_types = self.get_list_sous_types()
        if sous_types:
            for sous_type in sous_types:
                item = QListWidgetItem(sous_type[0])
                self.list_sous_types.addItem(item)

    def create_thematique(self):
        nom_thematique = self.edit_intitule.text()
        description = self.edit_description.toPlainText()
        categories = []
        for item in self.list_sous_types.selectedItems():
            stype = item.text()
            categories.append(f"{self.categorie}-{stype}")

        query = """
            select {}.qgis_creer_thematique({}, '{}', '{}', '{}', '{}', array{})
        """.format(
            self.db_schema_name,
            self.id_procedure,
            nom_thematique,
            description,
            self.classe["code"],
            self.categorie,
            categories,
        )
        md = QgsProviderRegistry.instance().providerMetadata("postgres")
        conn = md.createConnection(self.db_connection_uri, {})
        try:
            conn.executeSql(query)
            self.refreshCategories.emit()
            self.log(
                message=f"La thématique {nom_thematique} a été créée",
                log_level=Qgis.Success,
                push=True,
            )
            self.edit_intitule.setText("")
            self.edit_description.setText("")
        except QgsProviderConnectionException as e:
            self.log(
                message=catch_postgres_exception(str(e)),
                log_level=Qgis.Critical,
                push=True,
            )
