# -*- coding: utf-8 -*-
"""RUPP GEE LULC Toolkit - main plugin class."""

import os

from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QMessageBox, QInputDialog

from . import gee_utils as gu

ICON_DIR = os.path.join(os.path.dirname(__file__), "icons")


def _icon(name):
    path = os.path.join(ICON_DIR, name)
    return QIcon(path) if os.path.exists(path) else QIcon()


class RuppGeeLulcPlugin:
    def __init__(self, iface):
        self.iface = iface
        self.actions = []
        self.toolbar = None
        self.menu = "&GEE LULC Toolkit"
        self.loader_dlg = None
        self.sampling_dlg = None
        self.label_dock = None
        self.classify_dlg = None
        # shared session state (GEE objects live only in this session)
        self.state = {"stack": None, "aoi": None, "aoi_name": "",
                      "scale": None, "band_names": [], "classified": None}

    # ------------------------------------------------------------ setup
    def _add_action(self, text, callback, icon_name=None, on_toolbar=True):
        a = QAction(_icon(icon_name) if icon_name else QIcon(),
                    text, self.iface.mainWindow())
        a.setToolTip(text.replace("&&", "&"))
        a.triggered.connect(callback)
        self.iface.addPluginToMenu(self.menu, a)
        if on_toolbar and self.toolbar is not None:
            self.toolbar.addAction(a)
        self.actions.append(a)

    def initGui(self):
        self.toolbar = self.iface.addToolBar("GEE LULC Toolkit")
        self.toolbar.setObjectName("GeeLulcToolbar")
        self._add_action("GEE LULC Toolkit",
                         self.show_combined, "icon.png")
        self._add_action("Settings: GEE project ID",
                         self.settings, None, on_toolbar=False)
        self._add_action("Check Earth Engine connection",
                         self.check_ee, None, on_toolbar=False)

    def unload(self):
        for a in self.actions:
            self.iface.removePluginMenu(self.menu, a)
        self.actions = []
        if self.toolbar is not None:
            del self.toolbar
            self.toolbar = None
        if self.label_dock:
            self.iface.removeDockWidget(self.label_dock)
            self.label_dock = None

    # ------------------------------------------------------------ tools
    def show_combined(self):
        from .combined_dialog import CombinedLulcDialog
        if getattr(self, "_combined", None) is None:
            self._combined = CombinedLulcDialog(self.iface,
                                                self.iface.mainWindow())
        self._combined.show()
        self._combined.raise_()

    def show_loader(self):
        from .dialogs.loader_dialog import LoaderDialog
        if self.loader_dlg is None:
            self.loader_dlg = LoaderDialog(
                self.iface, self.state, self.iface.mainWindow())
        self.loader_dlg.show()
        self.loader_dlg.raise_()

    def show_sampling(self):
        from .dialogs.sampling_dialog import SamplingDialog
        if self.sampling_dlg is None:
            self.sampling_dlg = SamplingDialog(
                self.iface, self.iface.mainWindow(), self.state)
        self.sampling_dlg.show()
        self.sampling_dlg.raise_()

    def show_labeling(self):
        from .dialogs.labeling_dock import LabelingDock
        if self.label_dock is None:
            self.label_dock = LabelingDock(
                self.iface, self.iface.mainWindow())
            self.label_dock.state = self.state      # share the GEE stack
            self.iface.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.label_dock)
        self.label_dock.show()
        self.label_dock.load_layer()

    def show_classify(self):
        from .dialogs.classify_dialog import ClassifyDialog
        if self.classify_dlg is None:
            self.classify_dlg = ClassifyDialog(
                self.iface, self.state, self.iface.mainWindow())
        self.classify_dlg.show()
        self.classify_dlg.raise_()

    def show_signatures(self):
        from .dialogs.signatures_dialog import SignaturesDialog
        if getattr(self, "sig_dlg", None) is None:
            self.sig_dlg = SignaturesDialog(
                self.iface, self.state, self.iface.mainWindow())
        self.sig_dlg.show()
        self.sig_dlg.raise_()

    def make_layout(self):
        import traceback
        from qgis.PyQt.QtWidgets import QMessageBox
        try:
            from .lulc_adminmap import run_lulc_adminmap
            layout = run_lulc_adminmap(self.iface, self.state)
            if layout is not None:
                self.iface.openLayoutDesigner(layout)
        except RuntimeError as e:
            # boundaries data missing -> offer the simple layout instead
            ans = QMessageBox.question(
                self.iface.mainWindow(), "LULC Map Layout",
                str(e) + "\n\nBuild a simple layout instead?",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
            if ans == QMessageBox.StandardButton.Yes:
                from .layout_gen import make_layout
                make_layout(self.iface, self.state)
        except Exception as e:
            QMessageBox.critical(
                self.iface.mainWindow(), "LULC Map Layout",
                "{}\n\n{}".format(e, traceback.format_exc()))

    # ------------------------------------------------------------ settings
    def settings(self):
        pid, ok = QInputDialog.getText(
            self.iface.mainWindow(), "GEE project ID",
            "Google Cloud project registered for Earth Engine\n"
            "(leave empty to use the default credentials project):",
            text=gu.ee_project_id())
        if ok:
            gu.set_ee_project_id(pid.strip())

    def check_ee(self):
        try:
            ee = gu.init_ee()
            v = ee.String("Earth Engine is connected.").getInfo()
            QMessageBox.information(self.iface.mainWindow(), "GEE", v)
        except ImportError:
            QMessageBox.critical(
                self.iface.mainWindow(), "GEE",
                "The 'earthengine-api' package is not installed.\n\n"
                "Open the OSGeo4W Shell and run:\n"
                "    pip install earthengine-api\n"
                "Then restart QGIS.")
        except Exception as e:
            QMessageBox.critical(
                self.iface.mainWindow(), "GEE",
                "Could not connect to Earth Engine:\n{}\n\n"
                "Check your project ID in Settings, or run "
                "'earthengine authenticate' in the OSGeo4W Shell.".format(e))
