# -*- coding: utf-8 -*-
"""
/***************************************************************************
 MCDVisualizer
                                 A QGIS plugin
 Mars Climate Database (MCD) visualizer in QGIS
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2025-05-16
        git sha              : $Format:%H$
        copyright            : (C) 2025 by David Sánchez
        email                : david.sanchezruiz@edu.uah.es
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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
import os.path
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, Qt
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QMessageBox, QFileDialog
from qgis.core import QgsSettings

# Initialize Qt resources from file resources.py
from .resources import *

# Import the code for the DockWidget
from .mcd_visualizer_dockwidget import MCDVisualizerDockWidget

# Check if mandatory libraries are installed
try:
    import xarray as xr
    import netCDF4
except ImportError:
    xr = None


class MCDVisualizer:
    """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]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'MCDVisualizer_{}.qm'.format(locale))

        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'&MCD_Visualizer')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'MCDVisualizer')
        self.toolbar.setObjectName(u'MCDVisualizer')

        self.pluginIsActive = False
        self.dockwidget = None


    def tr(self, message):
        """Get the translation for a string using Qt translation API."""
        return QCoreApplication.translate('MCDVisualizer', 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."""

        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:
            self.toolbar.addAction(action)

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

        self.actions.append(action)

        return action


    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/mcd_visualizer/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'Select data'),
            callback=self.run,
            parent=self.iface.mainWindow())


    def onClosePlugin(self):
        """Cleanup necessary items here when plugin dockwidget is closed"""

        self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)
        self.pluginIsActive = False


    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""

        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&MCD_Visualizer'),
                action)
            self.iface.removeToolBarIcon(action)
        del self.toolbar


    def run(self):
        """Run method that loads and starts the plugin"""

        # ====================================================================
        # 1. DYNAMIC PATH MANAGEMENT & LIBRARIES CHECK
        # ====================================================================
        if xr is None:
            QMessageBox.critical(
                self.iface.mainWindow(),
                "Missing Libraries",
                "CRITICAL: 'xarray' and 'netCDF4' are missing.\n"
                "Please install them via OSGeo4W Shell: 'pip install xarray netCDF4'"
            )
            return

        settings = QgsSettings()
        ruta = settings.value("mcd_visualizer/data_path", "", type=str)

        while True:
            # Check if saved path is valid and contains essential subdirectories
            if (ruta and
                    os.path.exists(os.path.join(ruta, "clim_aveEUV")) and
                    os.path.exists(os.path.join(ruta, "MY24"))):
                settings.setValue("mcd_visualizer/data_path", ruta)
                break

            if ruta != "":
                QMessageBox.warning(
                    self.iface.mainWindow(),
                    "Invalid Path",
                    f"MCD database not found in:\n{ruta}\n\n"
                    "Please select the correct 'data' folder containing 'clim_aveEUV', 'MY24', etc."
                )
            else:
                QMessageBox.information(
                    self.iface.mainWindow(),
                    "Initial Setup",
                    "Please select your local MCD 'data' folder.\n"
                    "(It must contain ALL subfolders listed in the instructions)."
                )

            new_path = QFileDialog.getExistingDirectory(
                self.iface.mainWindow(),
                "Select MCD 'data' folder"
            )

            if not new_path:
                settings.remove("mcd_visualizer/data_path")
                QMessageBox.critical(
                    self.iface.mainWindow(),
                    "No Data Provided",
                    "No folder selected. MCD Visualizer will close as it cannot load data."
                )
                self.pluginIsActive = False
                return  # Abort run(), do NOT open the dockwidget

            ruta = new_path

        # ====================================================================
        # 2. DOCKWIDGET CREATION AND DISPLAY
        # ====================================================================
        if not self.pluginIsActive:
            self.pluginIsActive = True

            # Create dockwidget passing the validated 'ruta'
            if self.dockwidget is None:
                self.dockwidget = MCDVisualizerDockWidget(ruta)
            else:
                self.dockwidget.ruta = ruta  # Update path in case it changed

            # Connect to provide cleanup on closing of dockwidget
            self.dockwidget.closingPlugin.connect(self.onClosePlugin)

            # Show the dockwidget
            self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockwidget)
            self.dockwidget.show()
        else:
            self.dockwidget.hide()
            self.pluginIsActive = False