# -*- coding: utf-8 -*-

# QDraw: plugin that makes drawing easier
# Author: Jérémy Kalsron
#         jeremy.kalsron@gmail.com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from qgis.PyQt.QtCore import QCoreApplication, Qt
from qgis.PyQt.QtWidgets import QDialog, QComboBox, QLineEdit, QVBoxLayout, \
    QCheckBox, QDialogButtonBox, QLabel

from qgis.PyQt.QtCore import PYQT_VERSION_STR as pyqt_version  # Importer la version de PyQt

from qgis.core import QgsProject

import os, unicodedata, random

from .logger import log

class QDrawLayerDialog(QDialog):
    def __init__(self, iface, gtype, layerevt, evt):
        super().__init__()
        self.iface = iface
        from .logger import redirect_print_to_log
        redirect_print_to_log()
        self.setWindowTitle(self.tr('Drawing'))
        # Détermination du type de géométrie
        if gtype == 'text':
            self.gtype = 'text'
        elif gtype in ('point', 'XYpoint'):
            self.gtype = 'Point'
        elif gtype == 'line':
            self.gtype = 'LineString'
        else:
            self.gtype = 'Polygon'

        # Champ de saisie du nom
        self.name = QLineEdit()

        # Liste déroulante des couches disponibles
        self.layerBox = QComboBox()
        self.layers = []

        for layer in QgsProject.instance().mapLayers().values():
            # Couches mémoire uniquement
            # if layer.providerType() == "memory":
            #     # Vérifie le type de géométrie au lieu d'une chaîne fragile
            #     if self.gtype.lower() in layer.wkbType().name().lower():
            #         if 'field=' + self.tr('Drawings') + ':string(255,0)' in layer.dataProvider().dataSourceUri()[-28:]:
            #             self.layers.append(layer)
            #             self.layerBox.addItem(layer.name())
            if layer.type() == layer.VectorLayer:  # n'importe quelle couche vectorielle
                # if self.gtype.lower() in layer.wkbType().name().lower():
                if self.gtype.lower() in str(layer.wkbType()).lower():
                    self.layers.append(layer)
                    self.layerBox.addItem(layer.name())

            # Coche la couche d’événement passée en paramètre
            if layer.name() == layerevt:
                self.layers.append(layer)
                self.layerBox.addItem(layer.name())

        # Checkbox : ajouter à une couche existante
        self.addLayer = QCheckBox(self.tr('Add to an existing layer'))
        self.addLayer.toggled.connect(self.addLayerChecked)

        if not evt:
            self.addLayer.setEnabled(True)
            self.addLayer.setChecked(False)
        else:
            if self.gtype != 'text':
                self.addLayer.setEnabled(False)
                self.addLayer.setChecked(True)
            else:
                self.addLayer.setEnabled(False)
                self.addLayer.setChecked(False)

        # Boutons OK / Annuler
        buttons = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel,
            Qt.Orientation.Horizontal,
            self,
        )
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)

        # Layout principal
        vbox = QVBoxLayout()
        vbox.addWidget(QLabel(self.tr("Give a name to the item:")))
        vbox.addWidget(self.name)
        vbox.addWidget(self.addLayer)
        vbox.addWidget(self.layerBox)

        # Désactivation si aucune couche disponible
        if not self.layers:
            self.addLayer.setEnabled(False)
            self.layerBox.setEnabled(False)

        vbox.addWidget(buttons)
        self.setLayout(vbox)
        self.name.setFocus()

    def tr(self, message):
        return QCoreApplication.translate('QDrawLayerDialog', message)

    def addLayerChecked(self):
        self.layerBox.setEnabled(self.addLayer.isChecked())

    @staticmethod
    def getName(iface, gtype, layerevt, evt):
        dialog = QDrawLayerDialog(iface, gtype, layerevt, evt)
        result = dialog.exec()
        return (
            dialog.name.text(),
            dialog.addLayer.isChecked(),
            dialog.layerBox.currentIndex(),
            dialog.layers,
            result == QDialog.DialogCode.Accepted,
        )


class QDrawLayerDialogSelection(QDialog):
    def __init__(self, root, groupes_a_gerer=None):
        super().__init__()
        self.setWindowTitle(self.tr('Select'))

        self.groupes_a_gerer = groupes_a_gerer or []  # éviter NameError

        buttons = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel,
            Qt.Orientation.Horizontal,
            self,
        )
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)

        vbox = QVBoxLayout()
        vbox.addWidget(QLabel(self.tr("Drawing completed. Make a selection within its extent?")))
        vbox.addWidget(buttons)
        self.setLayout(vbox)

        # Récupération du projet et de la racine
        self.project = QgsProject.instance()
        self.root = self.project.layerTreeRoot()

    def tr(self, message):
        return QCoreApplication.translate('QDrawLayerDialogSelection', message)

    def getcoche(self):
        list_coche = []
        for group in self.root.children():
            test = ''.join(
                x for x in unicodedata.normalize('NFKD', group.name())
                if unicodedata.category(x)[0] == 'L'
            ).upper()
            if test not in self.groupes_a_gerer:
                coche = self.root.findGroup(group.name())
                if coche and coche.isVisible():
                    list_coche.append(True)
        return bool(list_coche)

