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

"""
/***************************************************************************
 DeteccionDePalmeras
                                 A QGIS plugin
 Este plug-in permite detectar automáticamente 3 especies de palmeras en imágenes RGB adquiridas con RPAs:aguaje (Mauritia flexuosa), huasai (Euterpe precautoria) y ungurahui (Oenocarpus bataua). 
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2021-10-06
        copyright            : (C) 2021 by Susan Palacios, Rodolfo Cardenas, Ximena Tagle
        email                : spalacios.salcedo@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.                                   *
 *                                                                         *
 ***************************************************************************/
"""

__author__ = 'Susan Palacios, Rodolfo Cardenas, Ximena Tagle'
__date__ = '2021-10-06'
__copyright__ = '(C) 2021 by Susan Palacios, Rodolfo Cardenas, Ximena Tagle'

# This will get replaced with a git SHA1 when you do a git archive

__revision__ = '$Format:%H$'

import os
import sys
import inspect

from qgis.PyQt.QtWidgets import QAction#icon
from qgis.PyQt.QtGui import QIcon#icon
import processing #icon
from qgis.core import QgsProcessingAlgorithm, QgsApplication
from .deteccion_de_palmeras_provider import DeteccionDePalmerasProvider

cmd_folder = os.path.split(inspect.getfile(inspect.currentframe()))[0]

if cmd_folder not in sys.path:
    sys.path.insert(0, cmd_folder)


class DeteccionDePalmerasPlugin(object):

    def __init__(self, iface):
        self.provider = None
        self.iface = iface


    def initProcessing(self):
        """Init Processing provider for QGIS >= 3.8."""
        self.provider = DeteccionDePalmerasProvider()
        QgsApplication.processingRegistry().addProvider(self.provider)

    def initGui(self):
        self.initProcessing()
        icon = os.path.join(os.path.join(cmd_folder, 'logo.png'))#icon
        self.action = QAction(
            QIcon(icon),
            u"Detección de Palmeras", self.iface.mainWindow())#icon
        self.action.triggered.connect(self.run)#icon
        self.iface.addPluginToMenu(u"&Palmeras", self.action)#icon
        self.iface.addToolBarIcon(self.action)#icon


    def unload(self):
        # Eliminar venv al desinstalar
        '''
        try:
            import shutil, os
            from ._env_core import EnvCore
            _envc = EnvCore(plugin_name='deteccion_de_palmeras_env')
            if _envc.venv_exists():
                vdir = os.path.dirname(_envc.venv_python)
                vroot = os.path.dirname(vdir)
                if os.path.isdir(vroot): shutil.rmtree(vroot, ignore_errors=True)
        except Exception:
            pass
        '''
        QgsApplication.processingRegistry().removeProvider(self.provider)
        self.iface.removePluginMenu(u"&Palmeras", self.action)#icon
        self.iface.removeToolBarIcon(self.action)#icon
        

    def run(self):#icon
        # Verificar dependencias antes de ejecutar el algoritmo
        try:
            from .palmeras_dependency import ensure_dependencies
            deps_ok = ensure_dependencies(self.iface)
            if deps_ok:
                processing.execAlgorithmDialog("Palmeras:Detección de Palmeras")
        except Exception as e:
            from qgis.PyQt.QtWidgets import QMessageBox
            QMessageBox.critical(
                self.iface.mainWindow(),
                "Error de Dependencias",
                "No se pudieron verificar las dependencias requeridas.\n\n" +
                str(e)
            )
