"""Main plugin class: registers a toolbar button + menu item that toggles the
AIS Guardian dock panel (three tabs: Guardian controls, event log, AIS stream)."""
import os

from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtCore import Qt

# QAction moved from QtWidgets (Qt5) to QtGui (Qt6). Try Qt6 first, fall back.
try:
    from qgis.PyQt.QtGui import QAction
except ImportError:
    from qgis.PyQt.QtWidgets import QAction

from .source_dialog import StreamWidget
from .guardian_dock import GuardianDock
from .guardian_store import GuardianStore


def _right_dock_area():
    """Qt.RightDockWidgetArea, enum-safe across Qt5/Qt6."""
    try:
        return Qt.RightDockWidgetArea
    except AttributeError:
        return Qt.DockWidgetArea.RightDockWidgetArea


class AisNmeaSourcePlugin:
    def __init__(self, iface):
        """Store the QGIS interface; GUI objects are created later in initGui."""
        self.iface = iface
        self.action = None
        self.dock = None
        self.store = None
        self.menu = "&AIS Watchkeeper"

    def initGui(self):
        """QGIS entry point: register the toolbar button + menu item and make the
        bundled vessel SVGs resolvable."""
        self._register_svg_path()
        icon_path = os.path.join(os.path.dirname(__file__), "icon.png")
        icon = QIcon(icon_path) if os.path.exists(icon_path) else QIcon()
        self.action = QAction(icon, "AIS Watchkeeper", self.iface.mainWindow())
        self.action.setToolTip("Show/hide the AIS Guardian panel "
                               "(keeps running in the background)")
        self.action.triggered.connect(self.toggle_panel)
        self.iface.addToolBarIcon(self.action)
        self.iface.addPluginToMenu(self.menu, self.action)

    def _register_svg_path(self):
        """Add the bundled symbols/ folder to QGIS's SVG search paths so the
        vessel SVGs resolve by filename on any machine (append-only)."""
        try:
            from qgis.core import QgsSettings
            settings = QgsSettings()
            sym_dir = os.path.join(os.path.dirname(__file__), "symbols")
            key = "svg/searchPathsForSVG"
            raw = settings.value(key)
            if raw is None:
                paths = []
            elif isinstance(raw, str):
                paths = raw.split("|") if raw else []
            else:
                paths = list(raw)
            if sym_dir not in paths:
                paths.append(sym_dir)
                settings.setValue(key, paths)
        except Exception:
            pass

    def unload(self):
        """QGIS exit point: stop background work and remove the dock + toolbar/
        menu entries."""
        if self.dock is not None:
            self.dock.shutdown()          # stop reader/scanner
            try:
                self.iface.removeDockWidget(self.dock)
            except Exception:
                pass
            self.dock.deleteLater()
            self.dock = None
        if self.action is not None:
            self.iface.removeToolBarIcon(self.action)
            self.iface.removePluginMenu(self.menu, self.action)
            self.action = None

    def toggle_panel(self):
        """Show/hide the Guardian dock, creating it on first use."""
        if self.dock is None:
            self._create_dock()
        # QgsDockWidget.setUserVisible toggles + raises the panel; fall back to
        # plain visibility if running against a build without it.
        if hasattr(self.dock, "isUserVisible"):
            self.dock.setUserVisible(not self.dock.isUserVisible())
        else:
            self.dock.setVisible(not self.dock.isVisible())

    def _create_dock(self):
        """Build the persistent store, the stream widget and the Guardian dock,
        and add the dock to the right-hand area. The store is best-effort: the
        panel still works (minus the log) if it can't be opened."""
        # Persistent store (target groups, event log, coverage). Best-effort:
        # if it can't be opened the panel still works, just without the log.
        try:
            self.store = GuardianStore()
            self.store.ensure_with_safeguards()
        except Exception:
            self.store = None
        stream = StreamWidget(self.iface, self.iface.mainWindow())
        self.dock = GuardianDock(self.iface, stream, store=self.store,
                                 parent=self.iface.mainWindow())
        self.iface.addDockWidget(_right_dock_area(), self.dock)
