from pathlib import Path

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

from plui_versionning.toolbelt import PlgLogger, PlgOptionsManager

colors = {
    "Référence": QColor(50, 150, 235),
    "En cours": QColor(235, 180, 50),
    "Figée": QColor(235, 65, 50),
    "Abandonnée": QColor(55, 55, 55),
    "Validée": QColor(20, 125, 10),
}


class VersionWidget(QWidget):
    def __init__(self, parent: QWidget = None):
        """
        QWidget Version

        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.version = None
        self.id_procedure = None
        self.projet = None
        self.list_version.currentItemChanged.connect(self.version_changed)
        self.wdg_version_details.setVisible(False)

    def refresh(self):
        """Force refresh of versions list"""
        self.fill_versions(self.id_procedure, self.projet)

    def get_procedure(self):
        """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

    def get_projet(self):
        """Return projet (id)"""
        # query = 'select id from "{}".pluiv_projets where id = {}'.format(
        #     self.db_schema_name, self.projet
        # )
        # 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
        return self.projet

    def get_thematique(self):
        return self.parent.parent().thematique

    def fill_versions(self, id_procedure: int, projet: int):
        # Clear list
        self.list_version.clear()
        self.id_procedure = id_procedure
        self.projet = projet

        if (id_procedure is None) or (projet is None):
            return

        query = """
            (SELECT pv.id, pv.id_version, pv.intitule, pvls.libelle
            FROM {}.pluiv_versions pv
            JOIN {}.pluiv_versionlibellestatut pvls on pv.statut = pvls.valeur
            WHERE id_projet = {}
            )
        """.format(
            self.db_schema_name, self.db_schema_name, projet
        )
        print(query)
        md = QgsProviderRegistry.instance().providerMetadata("postgres")
        conn = md.createConnection(self.db_connection_uri, {})
        try:
            result = conn.executeSql(query)
            for version in result:
                item = QListWidgetItem(
                    version[1] + " - " + version[2] + " (" + version[3] + ")"
                )
                item.setData(Qt.UserRole, version[0])
                item.setBackground(colors.get(version[3]))
                self.list_version.addItem(item)
        except QgsProviderConnectionException as e:
            self.log(message=e, log_level=Qgis.Critical, push=True)

    def version_changed(self, current, previous):
        """Event when user change version in list."""
        if not current:
            self.version = None
            return
        self.version = current.data(Qt.UserRole)
        self.set_version(self.version)

    def set_version(self, id_version: int):
        """Set version to display details

        Args:
            id_version (int): version id
        """
        self.wdg_version_details.setVisible(id_version is not None)
        self.wdg_version_details.set_version(id_version)
