import logging
# from qgis.gui import *

from qgis.core import (
    QgsDataSourceUri,
    QgsProject,
    QgsSettings,
    QgsVectorLayer,
    QgsMapThemeCollection,
)
from qgis.PyQt.QtCore import QSettings
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import (
    QDockWidget,
    QInputDialog,
)

from qgis.PyQt.QtXml import QDomDocument

try:
    Enabled = True
    from .tools.StyleLayer import host, port, dbname, os_user
except ValueError:
    Enabled = False
from .tools.resources import (
    load_ui,
    resources_path,
    # send_issues,
)
# from .issues import CenRa_Issues

# from datetime import date

EDITOR_CLASS = load_ui('CenRa_AutoMapStyle_base.ui')
LOGGER = logging.getLogger('CenRa_AutoMapStyle')


class AutoMap_Style(QDockWidget, EDITOR_CLASS):
    def __init__(self, parent=None):
        _ = parent
        super().__init__()
        self.setupUi(self)
        self.settings = QgsSettings()
        self.s = QSettings()

        self.toolButton.setIcon(QIcon(resources_path('icons', 'loader.png')))

        self.loadComboBox()
        self.toolButton.clicked.connect(self.loadStyle)

    def loadComboBox(self):
        style = self.comboBox
        style.clear()
        style.addItem('')
        style.addItem('Foncier')
        style.addItem('Administratif')

    def loadStyle(self):
        style = self.comboBox.currentText()
        if style == 'Foncier':
            self.loadFoncier()
        if style == 'Administratif':
            self.loadAdministratif()

    def loginfo(self):
        InputDialog = QInputDialog()
        mdp = InputDialog.getText(None, 'Foncier', 'Mot de pass base foncier:')
        return mdp

    def loadAdministratif(self):
        mtc = QgsProject.instance().mapThemeCollection()
        theme_name = 'Administratif'
        theme_state = mtc.mapThemeState(theme_name)

        mdp = self.loginfo()[0]
        if mdp != '':
            # couche = [['_form_power_rename','_form_power_rename_contour_2025'],['_42_bois_du_roy','_42_bois_du_roy_habitat_2021']]
            couche = [['administratif', 'departements2024', 'gid'], ['administratif', 'v_communes', 'id']]
            for schema_table in couche:
                schema = schema_table[0]
                table = schema_table[1]
                key = schema_table[2]
                uri = QgsDataSourceUri()
                uri.setConnection(host, port, dbname, os_user, mdp)
                # nom du schéma à remplacer: "hydrographie" à supprimer et mettre "couches_collaboratives" lorsqu'on aura regroupé les couches à modifier dans un même schéma
                uri.setDataSource(schema, table, "geom")
                uri.setKeyColumn(key)
                layer = QgsVectorLayer(uri.uri(), table, "postgres")
                if layer.isValid() is True:
                    layerName = layer.name()
                    listStyle = layer.listStylesInDatabase()
                    try:
                        StyleExist = True
                        indexStyle = (listStyle[2].index(layerName))
                    except ValueError:
                        StyleExist = False
                    if StyleExist:
                        StyleId = (listStyle[1][indexStyle])
                        styleTuple = layer.getStyleFromDatabase(StyleId)
                        styleqml = styleTuple[0]
                        styledoc = QDomDocument()
                        styledoc.setContent(styleqml)
                        layer.importNamedStyle(styledoc)

                    # Ajout de la couche au canevas QGIS
                    QgsProject.instance().addMapLayer(layer)

                    layer_record = QgsMapThemeCollection.MapThemeLayerRecord(layer)
                    theme_state.addLayerRecord(layer_record)
                    mtc.insert(theme_name, theme_state)

    def loadFoncier(self):
        mtc = QgsProject.instance().mapThemeCollection()
        theme_name = 'Foncier'
        theme_state = mtc.mapThemeState(theme_name)

        mdp = self.loginfo()[0]
        if mdp != '':
            # couche = [['_form_power_rename','_form_power_rename_contour_2025'],['_42_bois_du_roy','_42_bois_du_roy_habitat_2021']]
            couche = [['sites', 'v_sites_parcelles'], ['sites', 'v_sites'], ['inventaires', 'suivi_zh'], ['inventaires', 'suivi_ps']]
            for schema_table in couche:
                schema = schema_table[0]
                table = schema_table[1]
                uri = QgsDataSourceUri()
                uri.setConnection(host, port, dbname, os_user, mdp)
                # nom du schéma à remplacer: "hydrographie" à supprimer et mettre "couches_collaboratives" lorsqu'on aura regroupé les couches à modifier dans un même schéma
                uri.setDataSource(schema, table, "geom")
                uri.setKeyColumn('gid')
                layer = QgsVectorLayer(uri.uri(), table, "postgres")
                if layer.isValid() is True:
                    layerName = layer.name()
                    listStyle = layer.listStylesInDatabase()
                    try:
                        StyleExist = True
                        indexStyle = (listStyle[2].index(layerName))
                    except ValueError:
                        StyleExist = False
                    if StyleExist:
                        StyleId = (listStyle[1][indexStyle])
                        styleTuple = layer.getStyleFromDatabase(StyleId)
                        styleqml = styleTuple[0]
                        styledoc = QDomDocument()
                        styledoc.setContent(styleqml)
                        layer.importNamedStyle(styledoc)

                    # Ajout de la couche au canevas QGIS
                    QgsProject.instance().addMapLayer(layer)

                    layer_record = QgsMapThemeCollection.MapThemeLayerRecord(layer)
                    theme_state.addLayerRecord(layer_record)
                    mtc.insert(theme_name, theme_state)
