# -*- coding: utf-8 -*-
"""
/***************************************************************************
 SegSam
                                 A QGIS plugin
 generate poly using SAM
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2025-06-26
        git sha              : $Format:%H$
        copyright            : (C) 2025 by Ofer Butbega
        email                : geoosamplugin@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.                                   *
 *                                                                         *
 ***************************************************************************/
"""
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, Qt
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction

# Init Qt resources (generated by pyrcc5 resources.qrc -o resources_rc.py)
from .resources_rc import *

from .geo_osam_dialog import GeoOSAMControlPanel
import os.path


class SegSam:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """Constructor.

        :param iface: QgsInterface provided by QGIS.
        """
        self.iface = iface
        self.plugin_dir = os.path.dirname(__file__)

        # localisation
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir, 'i18n', f'SegSam_{locale}.qm')
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # housekeeping
        self.actions = []
        self.menu = self.tr('&GeoOSAM')
        self.first_start = None  # will be set in initGui()

        # Control panel instance
        self.control_panel = None

    # ---------------------------------------------------------------------
    # Helpers
    # ---------------------------------------------------------------------
    @staticmethod
    def tr(message: str) -> str:
        """Qt translation wrapper."""
        return QCoreApplication.translate('SegSam', message)

    def add_action(
            self,
            icon_path: str,
            text: str,
            callback,
            enabled_flag: bool = True,
            add_to_menu: bool = True,
            add_to_toolbar: bool = True,
            status_tip: str | None = None,
            whats_this: str | None = None,
            parent=None,
    ) -> QAction:
        """Add an icon to toolbar + menu and return the QAction."""
        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip:
            action.setStatusTip(status_tip)
        if whats_this:
            action.setWhatsThis(whats_this)

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

        self.actions.append(action)
        return action

    # ---------------------------------------------------------------------
    # QGIS mandatory hooks
    # ---------------------------------------------------------------------
    def initGui(self):
        """Create menu entries & toolbar icons."""
        icon_path = ':/plugins/geo_osam/icon.png'

        # Main action to show control panel
        self.add_action(
            icon_path,
            text=self.tr('Show Control Panel'),
            callback=self.show_control_panel,
            parent=self.iface.mainWindow(),
            status_tip=self.tr('Show GeoOSAM Control Panel')
        )

        # Additional action to toggle panel
        self.toggle_action = self.add_action(
            icon_path,
            text=self.tr('Toggle Panel'),
            callback=self.toggle_control_panel,
            parent=self.iface.mainWindow(),
            status_tip=self.tr('Toggle GeoOSAM Control Panel visibility'),
            add_to_toolbar=False  # Only in menu
        )

        self.first_start = True

    def unload(self):
        """Remove plugin UI elements on unload."""
        # Remove control panel
        if self.control_panel:
            self.control_panel.close()
            self.control_panel = None

        # Remove actions
        for action in self.actions:
            self.iface.removePluginMenu(self.menu, action)
            self.iface.removeToolBarIcon(action)

    # ---------------------------------------------------------------------
    # Control Panel Management
    # ---------------------------------------------------------------------
    def show_control_panel(self):
        """Show the GeoOSAM control panel"""
        if not self.control_panel:
            self.control_panel = GeoOSAMControlPanel(self.iface)
            # Dock it to the right side
            self.iface.addDockWidget(
                Qt.RightDockWidgetArea, self.control_panel)

            # Connect to closed signal to clean up reference
            self.control_panel.destroyed.connect(self._on_panel_destroyed)

        # Show and raise the panel
        self.control_panel.show()
        self.control_panel.raise_()

        # Update status in QGIS
        self.iface.messageBar().pushMessage(
            "GeoOSAM",
            "🛰️ Control panel opened. Select a class and segmentation mode to begin.",
            duration=5
        )

    def toggle_control_panel(self):
        """Toggle control panel visibility"""
        if not self.control_panel:
            self.show_control_panel()
        else:
            if self.control_panel.isVisible():
                self.control_panel.hide()
                self.iface.messageBar().pushMessage(
                    "GeoOSAM", "Control panel hidden", duration=3)
            else:
                self.control_panel.show()
                self.control_panel.raise_()
                self.iface.messageBar().pushMessage(
                    "GeoOSAM", "Control panel shown", duration=3)

    def _on_panel_destroyed(self):
        """Handle control panel being destroyed"""
        self.control_panel = None

    # ---------------------------------------------------------------------
    # Legacy compatibility (for existing installations)
    # ---------------------------------------------------------------------
    def run(self):
        """Legacy method - redirects to control panel"""
        self.show_control_panel()
