# -*- coding: utf-8 -*-
"""
/***************************************************************************
 Siligites
                                 A QGIS plugin
 Extension for the study of the proximity between archaeological sites and related silicite geological formations
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2024-06-03
        git sha              : $Format:%H$
        copyright            : (C) 2024 by Thomas ANDRE
        email                : thomas.andre.archgeo@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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction

# Initialize Qt resources from file resources.py
from .resources import *
# Import the code for the dialog
from .Silextracteur.Silextracteur_dialog import SilextracteurDialog
from .SilLCP.SilLCP_dialog import SilLCPDialog
from .Silanalyses.Silanalyses_dialog import SilanalysesDialog
from .Siliguide.Siliguide_dialog import SiliguideDialog
from .SiliciteR.Provider import SiliciteR

import os
import time
import configparser
import shutil

from qgis import *
from qgis.PyQt import *
from qgis.core import *
from qgis.utils import *
from qgis.PyQt.QtGui import *
from qgis.PyQt.QtCore import *
from qgis.PyQt.QtWidgets import *
from qgis.PyQt.QtCore import *

import processing
from .Fonctions.Utilitaires import *
from .Fonctions.Fonctions_QGIS import *


class Siligites:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """
        Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface

        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        if locale == "fr":
            locale_path = os.path.join(self.plugin_dir, 'i18n', 'Siligites_fr.qm')
        else:
            locale_path = os.path.join(self.plugin_dir, 'i18n', 'Siligites_en.qm')

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Siligites')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start1 = None
        self.first_start2 = None
        self.first_start3 = None
        self.first_start4 = None
        
        self.iface = iface


    # noinspection PyMethodMayBeStatic
    @staticmethod
    def tr(message):
        """
        Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate("SiligitesDialogBase", message)


    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):
        """
        Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            # Adds plugin icon to Plugins toolbar
            self.toolBar.addAction(action)

        if add_to_menu:
            self.iface.addPluginToMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action


    def initGui(self):
        """
        Creates application GUI widgets
        """

        """Specific actions if the extension is installed/reload from the extension window"""
        if self.iface.mainWindow().isVisible():

            """Preparations of the tools for the first loading of the extension"""
            metadata = configparser.ConfigParser()
            metadata.read(os.path.join(self.plugin_dir, "metadata.txt"))
            current_version = metadata["general"]["version"]
            admin_version = metadata["general"]["version_admin"]
            # print(current_version) # debugtest
            stored_version = QSettings().value("Siligites/version", None)
            # print(stored_version) # debugtest
            layers_version = QSettings().value("Siligites/admin", None)


            """Deleting useless layers from past versions"""
            try:
                layers_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Couches')
                extensions_shapefile = (".shp", ".shx", ".dbf", ".prj", ".cpg", ".qix", ".sbn", ".sbx", ".xml")
                # print(layers_path) # debugtest
                if not os.path.isdir(layers_path):
                    os.mkdir(layers_path)
                for nom in os.listdir(layers_path):
                    chemin_complet = os.path.join(layers_path, nom)
                    # print(chemin_complet)
                    if os.path.isdir(chemin_complet):
                        shutil.rmtree(chemin_complet)
                    if nom.lower().endswith(extensions_shapefile):
                        os.remove(os.path.join(layers_path, nom))
            except Exception:
                pass


            """Gestion of the versions of the plugin and layers"""
            new_version = False
            if stored_version != current_version:
                QSettings().setValue("Siligites/version", current_version)
                QSettings().sync()
                new_version = True

            new_layers = False
            if layers_version != admin_version:
                try :
                    for file in os.listdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Couches')):
                        if file.startswith("Departements") or file.startswith("Communes"):
                            os.remove(os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Couches'), file))
                    QSettings().setValue("Siligites/admin", admin_version)
                    QSettings().sync()
                    new_layers = True
                except Exception:
                    pass


            """Gestion of some names for the Provider"""
            name = os.path.basename(os.path.dirname(__file__))
            old = "siligites.SiliciteR.processing.script_editor_widget"
            new = f"{name}.SiliciteR.processing.script_editor_widget"
            ui_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'SiliciteR/processing/DlgScriptEditor.ui')

            with open(ui_path, "r", encoding="utf-8") as f:
                content = f.read()

            content = content.replace(old, new)

            with open(ui_path, "w", encoding="utf-8") as f:
                f.write(content)


            """Creation of a loading window to give informations"""
            self.progress_dialog = QProgressDialog(QCoreApplication.translate("SiligitesDialogBase", "Chargement en cours... Le téléchargement des données peut prendre quelques minutes"),
                                            None, 0, 100)
            self.progress_dialog.setWindowModality(Qt.WindowModality.WindowModal)
            self.progress_dialog.setWindowTitle(QCoreApplication.translate("SiligitesDialogBase", "Veuillez patienter... Le téléchargement des données peut prendre quelques minutes"))
            self.progress_dialog.setWindowModality(Qt.WindowModality.ApplicationModal)
            self.progress_dialog.setCancelButton(None)
            
            if hasattr(Qt, "WindowCloseButtonHint"):
                self.progress_dialog.setWindowFlag(Qt.WindowCloseButtonHint, False)
            else:
                self.progress_dialog.setWindowFlag(Qt.WindowType.WindowCloseButtonHint, False)

            self.progress_dialog.setValue(0)
            self.progress_dialog.show()
            QCoreApplication.processEvents()


            """Initialisation of the extension"""  
            self.choix = None      
            if new_version and new_layers:
                #Giving the user the choice to download the default layers or not
                self.user_choice()
            
            # Preparation for the possible downloading of the utility layers from the WFS
            if self.choix == "Download":
                path = os.path.dirname(os.path.abspath(__file__))
                path = path + '//Couches//'
                # Checking the presence or not of the different utility layers
                t0 = time.time() # debugtest
                self.progressions(25, QCoreApplication.translate("SiligitesDialogBase", "Téléchargement de la couche des départements français..."))
                Utilitaires.recuperation(self, path, 'Departements')
                # print(1,time.time()-t0) # debugtest
                self.progressions(50, QCoreApplication.translate("SiligitesDialogBase", "Téléchargement de la couche des communes françaises..."))
                Utilitaires.recuperation(self, path, 'Communes')
                # print(2,time.time()-t0) # debugtest

            
        """Preparation of the provider to access R"""
        self.progressions(75, QCoreApplication.translate("SiligitesDialogBase", "Mise en place du provider pour faire le lien avec R..."))
        self.provider = SiliciteR()
        QgsApplication.processingRegistry().addProvider(self.provider)
        self.progressions(99, QCoreApplication.translate("SiligitesDialogBase", "Chargement des différents outils..."))

        for provider in QgsApplication.processingRegistry().providers():
            provider.refreshAlgorithms()


        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        self.toolBar = self.iface.addToolBar("Siligites")
        self.toolBar.setObjectName("Siligites")

        # Gestion of the buttons and icons
        path = os.path.dirname(os.path.abspath(__file__))

        icon_path = os.path.join(path, 'Logos//Silextracteur.png')
        self.add_action(
            icon_path,
            text = QCoreApplication.translate("SiligitesDialogBase", u'Silextracteur'),
            callback = self.run1,
            parent = self.iface.mainWindow())
        
        icon_path = os.path.join(path, 'Logos//SilLCP.png')
        self.add_action(
            icon_path,
            text = QCoreApplication.translate("SiligitesDialogBase", u'SilLCP'),
            callback = self.run2,
            parent = self.iface.mainWindow())
        
        icon_path = os.path.join(path, 'Logos//Silanalyses.png')
        self.add_action(
            icon_path,
            text = QCoreApplication.translate("SiligitesDialogBase", u'Silanalyses'),
            callback = self.run3,
            parent = self.iface.mainWindow())
        
        icon_path = os.path.join(path, 'Logos//Siliguide.png')
        self.add_action(
            icon_path,
            text = QCoreApplication.translate("SiligitesDialogBase", u'Siliguide'),
            callback = self.run4,
            parent = self.iface.mainWindow())

        # will be set False in run()
        self.first_start1 = True
        self.first_start2 = True
        self.first_start3 = True
        self.first_start4 = True

        self.progressions(100, QCoreApplication.translate("SiligitesDialogBase","Terminé !"))


        """Message to explain why the tool to create R scripts is absent or doesn't work after activation"""
        if self.iface.mainWindow().isVisible():
            message = QCoreApplication.translate("SiligitesDialogBase","Installation terminée. Pour utiliser l'outil de création/modification de scripts R, il est cependant nécessaire de relancer une nouvelle fenêtre QGIS")
            QMessageBox.information( None, "Information SiliciteR", message)



    def progressions(self, progress, message):
        """
        Update the progress of the loading during launch

        :param progress: New progress of the bar
        :type progress: int

        :param message: Message to print
        :type message: str
        """
        try:
            self.progress_dialog.setLabelText(message)
            self.progress_dialog.setValue(progress)
            QCoreApplication.processEvents()
        except Exception:
            pass

    
    def user_choice(self):
        dlg = QDialog()
        dlg.setWindowTitle(QCoreApplication.translate("SiligitesDialogBase", "Télécharger les couches de données par défaut ?"))

        Dialog = Qt.Dialog if hasattr(Qt, "Dialog") else Qt.WindowType.Dialog
        Customize = (
            Qt.CustomizeWindowHint
            if hasattr(Qt, "CustomizeWindowHint")
            else Qt.WindowType.CustomizeWindowHint
        )
        Title = (
            Qt.WindowTitleHint
            if hasattr(Qt, "WindowTitleHint")
            else Qt.WindowType.WindowTitleHint
        )

        dlg.setWindowFlags(
            Qt.WindowFlags(
                Dialog | Customize | Title
            )
        )
        dlg.setMinimumWidth(420)

        text_layout = QVBoxLayout(dlg)

        message = "\n".join([
                QCoreApplication.translate("SiligitesDialogBase", "Siligîtes vous propose d'utiliser des données par défaut pour vos analyses."),
                QCoreApplication.translate("SiligitesDialogBase", "Vous pouvez soit les télécharger maintenant (stockage au sein de l'extension),"),
                QCoreApplication.translate("SiligitesDialogBase", "soit utiliser leurs versions en ligne et/ou les télécharger plus tard")
            ])
        label = QLabel(message)
        label.setWordWrap(True)
        label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        label.setStyleSheet("font-weight: bold;")
        text_layout.addWidget(label)

        message = "\n".join([QCoreApplication.translate("SiligitesDialogBase", "Télécharger les données maintenant : Le plugin prendra plus de temps à s'installer, mais le temps de traitement des outils lors de leur utilisation ne sera pas affecté"),
                        "",
                        QCoreApplication.translate("SiligitesDialogBase", "OU"),
                        "",
                        QCoreApplication.translate("SiligitesDialogBase", "Passer et utiliser les versions en ligne : Installation plus rapide, mais la performance de certains outils peut être affectée pendant quelques minutes après le chargement des couches dans le projet"),
                        ""
            ])
        label = QLabel(message)
        label.setWordWrap(True)
        label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        text_layout.addWidget(label)

        btn_layout = QHBoxLayout()
        btn_layout.addStretch()

        btn_a = QPushButton(QCoreApplication.translate("SiligitesDialogBase", "Télécharger"))
        btn_b = QPushButton(QCoreApplication.translate("SiligitesDialogBase", "Passer"))

        btn_layout.addWidget(btn_a)
        btn_layout.addSpacing(30)
        btn_layout.addWidget(btn_b)

        btn_layout.addStretch()
        text_layout.addLayout(btn_layout)

        btn_a.clicked.connect(lambda: (setattr(self, "choix", "Download"), dlg.accept()))
        btn_b.clicked.connect(lambda: (setattr(self, "choix", "Skip"), dlg.accept()))

        if dlg.exec() != getattr(dlg, "Accepted", dlg.DialogCode.Accepted):
            self.choix = None


    def unload(self):
        """
        Removes the plugin menu item and icon from QGIS GUI.
        """
        for action in self.actions:
            self.iface.removePluginMenu(
                QCoreApplication.translate("SiligitesDialogBase", u'Silextracteur'),
                action)
            self.iface.removePluginMenu(
                QCoreApplication.translate("SiligitesDialogBase", u'SilLCP'),
                action)
            self.iface.removePluginMenu(
                QCoreApplication.translate("SiligitesDialogBase", u'Silanalyses'),
                action)
            self.iface.removePluginMenu(
                QCoreApplication.translate("SiligitesDialogBase", u'Siliguide'),
                action)
            self.iface.removeToolBarIcon(action)
        del self.toolBar
        QgsApplication.processingRegistry().removeProvider(self.provider)


    def run1(self):
        """
        Run method that performs all the real work
        """
        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start1 == True:
            self.first_start1 = False
            self.dlg1 = SilextracteurDialog()

        # show the dialog
        self.dlg1.show()
        # # Run the dialog event loop
        # result = self.dlg1.exec_()
        # # See if OK was pressed
        # if result:
        #     # Do something useful here - delete the line containing pass and
        #     # substitute with your code.
        #     pass
    
    def run2(self):
        """
        Run method that performs all the real work
        """
        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start2 == True:
            self.first_start2 = False
            self.dlg2 = SilLCPDialog()

        # show the dialog
        self.dlg2.show()
        # # Run the dialog event loop
        # result = self.dlg2.exec_()
        # # See if OK was pressed
        # if result:
        #     # Do something useful here - delete the line containing pass and
        #     # substitute with your code.
        #     pass

    def run3(self):
        """
        Run method that performs all the real work
        """
        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start3 == True:
            self.first_start3 = False
            self.dlg3 = SilanalysesDialog()

        # show the dialog
        self.dlg3.show()
        # # Run the dialog event loop
        # result = self.dlg3.exec_()
        # # See if OK was pressed
        # if result:
        #     # Do something useful here - delete the line containing pass and
        #     # substitute with your code.
        #     pass

    def run4(self):
        """
        Run method that performs all the real work
        """
        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start4 == True:
            self.first_start4 = False
            self.dlg4 = SiliguideDialog()

        # show the dialog
        self.dlg4.show()
        # # Run the dialog event loop
        # result = self.dlg4.exec()
        # # See if OK was pressed
        # if result:
        #     # Do something useful here - delete the line containing pass and
        #     # substitute with your code.
        #     pass
