# -*- coding: utf-8 -*-
"""
/***************************************************************************
 AhpAnalysis
                                 A QGIS plugin
 QGIS plugin for hierarchical multi-criteria analysis (AHP – Saaty method) using raster layers
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2025-12-20
        git sha              : $Format:%H$
        copyright            : (C) 2025 by Sewedo GNANSOUNOU
        email                : sewedo.gnansounou@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.                                   *
 *                                                                         *
 ***************************************************************************/
"""


import os

from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QToolBar

# Qt resources
from .resources import *

# Dialogue principal
from .ahp_analysis_dialog import AhpAnalysisDialog


class AhpAnalysis:
    """Implémentation principale du plugin QGIS."""

    def __init__(self, iface):
        """Constructeur."""
        self.iface = iface
        self.plugin_dir = os.path.dirname(__file__)
        self.actions = []
        self.menu = self.tr('&Analyse AHP Raster ')

        # Traduction
        locale = QSettings().value('locale/userLocale', 'en')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            f'AhpAnalysis_{locale}.qm'
        )

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

        self.dlg = None  # Dialogue créé au premier lancement

    def tr(self, message):
        """Traduction."""
        return QCoreApplication.translate('AhpAnalysis', message)

    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        parent=None
    ):
        """Ajoute une action au menu et à la barre d’outils."""
        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if add_to_toolbar:
            self.iface.addToolBarIcon(action)

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

        self.actions.append(action)
        return action

    def initGui(self):
        """Initialisation GUI."""
        icon_path = ':/plugins/ahp_analysis/icon2.png'
        self.add_action(
            icon_path,
            text=self.tr('Analyse AHP Raster'),
            callback=self.run,
            parent=self.iface.mainWindow()
        )
        # Mettre à jour l'icône si nécessaire
        # Par exemple avec un nouveau fichier
        self.update_icon(':/plugins/ahp_analysis/icon2.png')
        
    def unload(self):
        """Nettoyage du plugin."""
        for action in self.actions:
            self.iface.removePluginMenu(self.menu, action)
            self.iface.removeToolBarIcon(action)

    def _on_dialog_closed(self):
        """Détruit complètement le dialogue."""
        self.dlg.deleteLater()
        self.dlg = None

    def update_icon(self, new_icon_path):
        """Met à jour l’icône du plugin dans le menu et la barre d’outils."""
        # Supprimer toutes les actions existantes
        for action in self.actions:
            self.iface.removePluginMenu(self.menu, action)
            self.iface.removeToolBarIcon(action)
            action.deleteLater()
        self.actions = []

        # Créer une nouvelle action avec la nouvelle icône
        self.add_action(
            new_icon_path,
            text=self.tr('Analyse AHP Raster'),
            callback=self.run,
            parent=self.iface.mainWindow()
        )

        # Rafraîchir la GUI
        self.iface.mainWindow().menuBar().repaint()
        for tb in self.iface.mainWindow().findChildren(QToolBar):
            tb.repaint()

    # ======================================================
    # ===================== UI RUN =========================
    # ======================================================

    def run(self):
        """Ouvre le dialogue AHP (nouvelle instance à chaque fois)."""
        self.dlg = AhpAnalysisDialog(self.iface.mainWindow())

        # À la fermeture → destruction complète
        self.dlg.finished.connect(self._on_dialog_closed)

        self.dlg.show()
        self.dlg.raise_()
        self.dlg.activateWindow()
