"""Main plugin entry point: registers the Processing provider and the dock panel."""

from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtWidgets import QAction
from qgis.PyQt.QtGui import QIcon
from qgis.core import QgsApplication
import os

from .provider import ShorelineProvider
from .gui.dock_widget import ShorelineDockWidget


class ShorelineHovmollerPlugin:
    def __init__(self, iface):
        self.iface = iface
        self.provider = None
        self.dock = None
        self.action = None
        self.plugin_dir = os.path.dirname(__file__)

    # --- Processing provider ---
    def initProcessing(self):
        self.provider = ShorelineProvider()
        QgsApplication.processingRegistry().addProvider(self.provider)

    def initGui(self):
        self.initProcessing()

        icon = QIcon(os.path.join(self.plugin_dir, 'icons', 'icon.svg'))
        self.action = QAction(icon, 'Shoreliser Panel', self.iface.mainWindow())
        self.action.setCheckable(True)
        self.action.triggered.connect(self.toggle_panel)
        self.iface.addToolBarIcon(self.action)
        self.iface.addPluginToMenu('Shoreliser', self.action)

        # Build dock but keep hidden until toggled
        self.dock = ShorelineDockWidget(self.iface)
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock)
        self.dock.hide()
        self.dock.visibilityChanged.connect(self.action.setChecked)

    def toggle_panel(self, checked):
        self.dock.setVisible(checked)

    def unload(self):
        if self.provider:
            QgsApplication.processingRegistry().removeProvider(self.provider)
        if self.action:
            self.iface.removeToolBarIcon(self.action)
            self.iface.removePluginMenu('Shoreliser', self.action)
        if self.dock:
            self.iface.removeDockWidget(self.dock)
            self.dock.deleteLater()
