from pathlib import Path

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

from plui_versionning.gui.wdg_tab_thematique import Thematique
from plui_versionning.toolbelt import PlgLogger, PlgOptionsManager


class ProjetWidget(QWidget):
    showVersionDetails = pyqtSignal(int)

    def __init__(self, parent: QWidget = None):
        """
        QWidget Projet

        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.projet = None
        self.list_projet.currentItemChanged.connect(self.projet_changed)
        self.wdg_projet_details.setVisible(False)
        self.wdg_projet_details.showVersionDetails.connect(self.showVersionDetails)

    def fill_projets(self, id_procedure: int, thematique: Thematique):
        # Clear list
        self.list_projet.clear()

        if id_procedure is None:
            return

        self.id_procedure = id_procedure

        query = """
            (SELECT p.id, p.nom_projet FROM {0}.pluiv_projets p
            JOIN {0}.pluiv_corresp_procedures_thematiques pcpt on p.id_proc_them = pcpt.id_thematique
            WHERE pcpt.id_procedure = {1} AND p.categorie LIKE '{2}%')
            """.format(
            self.db_schema_name, str(id_procedure), thematique["thematique"]
        )
        print(query)
        md = QgsProviderRegistry.instance().providerMetadata("postgres")
        conn = md.createConnection(self.db_connection_uri, {})
        try:
            result = conn.executeSql(query)
            for projet in result:
                item = QListWidgetItem(projet[1])
                item.setData(Qt.UserRole, projet[0])
                self.list_projet.addItem(item)
        except QgsProviderConnectionException as e:
            self.log(message=e, log_level=Qgis.Critical, push=True)

    def projet_changed(self, current, previous):
        """Event when user change projet in list."""
        if not current:
            self.projet = None
            return
        self.projet = current.data(Qt.UserRole)
        self.wdg_projet_details.setVisible(self.projet is not None)
        self.wdg_projet_details.set_projet(self.projet)
        self.parent.parent().wdg_version.fill_versions(self.id_procedure, self.projet)

    def refresh(self):
        """Force refresh of projets list"""
        self.parent.parent().refresh(self.id_procedure)

    def show_version_details(self, id_version: int):
        """Show version details

        Args:
            id_version (int): version id
        """
        self.parent.parent().set_version(id_version)
