# -*- coding: utf-8 -*-
"""
/***************************************************************************
 AGLgis
                                 A QGIS plugin
 DEM
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2026-04-01
        git sha              : $Format:%H$
        copyright            : (C) 2026 by FARM Analytica
        email                : livia.scopel@farmanalytica.com.br
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.path

from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction
from qgis.PyQt.QtCore import QCoreApplication, QTranslator
from qgis.core import QgsSettings

from .aglgis_dialog import AGLgisDialog
from .managers.settings_manager import SettingsManager


class AGLgis:
    """
    Main plugin class for AGLgis QGIS plugin.

    Manages plugin initialization, GUI setup, and authentication workflow.
    """

    def __init__(self, interface):

        self.interface = interface
        self.plugin_dir = os.path.dirname(__file__)
        self.actions = []
        self.menu = "&AGLgis"

        self.first_start = None
        self._waiting_for_extlibs = False
        self._services_ready = False

        locale = QgsSettings().value("locale/userLocale", "en_US")
        language = locale[:2]
        locale_map = {"pt": "pt_BR", "zh": "zh_CN"}
        qm_language = locale_map.get(language, language)
        self._translator = QTranslator()
        qm_path = os.path.join(self.plugin_dir, "i18n", f"aglgis_{qm_language}.qm")
        if os.path.exists(qm_path):
            self._translator.load(qm_path)
            QCoreApplication.installTranslator(self._translator)

    def tr(self, message):
        """
        Translate a message string.

        Args:
            message: Message to translate.

        Returns:
            Translated message string.
        """
        return QCoreApplication.translate("AGLgis", 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 an action to the toolbar and/or menu.

        Args:
            icon_path: Path to the action icon.
            text: Action display text.
            callback: Function to call when action is triggered.
            enabled_flag: Whether action is enabled initially.
            add_to_menu: Whether to add action to plugin menu.
            add_to_toolbar: Whether to add action to toolbar.
            status_tip: Tooltip text.
            whats_this: Help text.
            parent: Parent widget.

        Returns:
            The created QAction object.
        """

        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.interface.addToolBarIcon(action)

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

        self.actions.append(action)

        return action

    def initGui(self):
        """Initialize the plugin GUI."""
        icon_path = os.path.join(self.plugin_dir, "icon.png")
        self.add_action(
            icon_path,
            text=self.tr(""),
            callback=self.run,
            parent=self.interface.mainWindow(),
        )

        self.first_start = True

    def unload(self):
        """Remove the plugin from QGIS."""
        QCoreApplication.removeTranslator(self._translator)
        for action in self.actions:
            self.interface.removePluginMenu("&AGLgis", action)
            self.interface.removeToolBarIcon(action)

    def _finish_init(self):
        from .services.gee_service import GEEService
        from .controllers.dem_ctrl import DEMCtrl
        from .controllers.auth_ctrl import AuthCtrl
        from .controllers.sar_ctrl import SARCtrl

        self._services_ready = True
        self.gee_service = GEEService()
        self.dem_ctrl = DEMCtrl(self.dialog, self.gee_service, self.interface)
        self.auth_ctrl = AuthCtrl(self.dialog, self.gee_service)
        self.sar_ctrl = SARCtrl(self.dialog, self.interface, self.gee_service)

        saved_project_id = self.gee_service.get_saved_project_id()
        if saved_project_id:
            self.dialog.project_id_input.setText(saved_project_id)

        saved_folder = SettingsManager.load_download_folder()
        if saved_folder:
            self.dialog.folder_input.setText(saved_folder)

        self.dialog.project_id_input.textChanged.connect(
            self.gee_service.save_project_id
        )
        self.dialog.project_id_input.textChanged.connect(
            self.auth_ctrl.on_project_id_changed
        )
        self.dialog.btn_authenticate.clicked.connect(
            self.auth_ctrl.handle_authentication
        )
        self.dialog.btn_reset_auth.clicked.connect(
            self.auth_ctrl.handle_reset_authentication
        )
        self.dialog.auth_status_badge.clicked.connect(
            self.auth_ctrl.refresh_auth_status
        )
        self.dialog.btn_browse_folder.clicked.connect(
            self.auth_ctrl.handle_folder_selection
        )
        self.dialog.btn_clear_folder.clicked.connect(self.auth_ctrl.handle_clear_folder)
        self.dialog.btn_go_to_aoi.clicked.connect(self.dem_ctrl.load_available_datasets)

        self.dialog.layer_combo.layerChanged.connect(self.dem_ctrl.handle_layer_changed)
        self.dialog.dem_combo.currentIndexChanged.connect(
            self.dem_ctrl.on_dataset_changed
        )
        self.dialog.btn_download_dem.clicked.connect(
            lambda: self.dem_ctrl.handle_dem_service(self.interface)
        )
        self.dialog.btn_hybrid_layer.clicked.connect(self.dem_ctrl.handle_hybrid_layer)
        self.dialog.btn_draw_aoi.clicked.connect(self.dem_ctrl.handle_draw_aoi)

        self.dialog.sar_btn_hybrid_layer.clicked.connect(
            self.dem_ctrl.handle_hybrid_layer
        )
        self.dialog.sar_btn_draw_aoi.clicked.connect(self.sar_ctrl.handle_draw_aoi)
        self.dialog.sar_btn_next.clicked.connect(self.sar_ctrl.handle_sar_run)
        self.dialog.sar_btn_preview.clicked.connect(self.sar_ctrl.handle_preview_image)
        self.dialog.sar_btn_download_preview.clicked.connect(
            self.sar_ctrl.handle_download_preview
        )
        self.dialog.sar_btn_open_browser.clicked.connect(
            self.sar_ctrl.handle_open_browser
        )
        self.dialog.sar_btn_download_csv.clicked.connect(
            self.sar_ctrl.handle_export_csv
        )
        self.dialog.sar_btn_batch_download.clicked.connect(
            self.sar_ctrl.handle_batch_download
        )
        self.dialog.sar_btn_filter_dates.clicked.connect(
            self.sar_ctrl.handle_filter_dates
        )
        self.dialog.sar_btn_composite_preview.clicked.connect(
            self.sar_ctrl.handle_composite_preview
        )
        self.dialog.sar_btn_composite_download.clicked.connect(
            self.sar_ctrl.handle_composite_download
        )
        self.dialog.sar_layer_combo.layerChanged.connect(
            self.sar_ctrl.handle_layer_changed
        )

        self.auth_ctrl.refresh_auth_status()

    def _on_extlibs_ready(self, success, error_msg):
        self._waiting_for_extlibs = False
        if success:
            from . import extlibs_manager

            extlibs_manager.ensure_on_path()
            self._finish_init()
            self.dialog.show_auth_page()
        else:
            self.dialog.pop_message(
                self.tr("Failed to download dependencies: %s") % error_msg,
                "warning",
            )

    def run(self):
        """Display the plugin dialog and handle user interaction."""
        from . import extlibs_manager

        if self.first_start:
            self.first_start = False
            self.dialog = AGLgisDialog(None)

        if not self._services_ready:
            if extlibs_manager.is_ready():
                extlibs_manager.ensure_on_path()
                self._finish_init()
            else:
                self.dialog.show_loading_page()
                downloader = extlibs_manager.get_downloader()
                if downloader and not self._waiting_for_extlibs:
                    self._waiting_for_extlibs = True
                    downloader.download_done.connect(self._on_extlibs_ready)

        self.dialog.show()
        self.dialog.raise_()
        self.dialog.activateWindow()
