"""QGIS plugin entry for Beaver processor.

Standard QGIS plugin lifecycle: ``classFactory`` (in __init__.py) returns a
``BeaverProcessorPlugin``; QGIS calls ``initGui()`` on load and ``unload()``
on removal. The map builder opens as a dialog parented to the QGIS main
window and never touches the user's open project (it works on its own
private QgsProject — see core_project.py).
"""

import os

from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QAction, QDialog, QVBoxLayout

_HERE = os.path.dirname(os.path.abspath(__file__))
# Resources (icon, project, assets) live at the package root, one level up.
_PKG_ROOT = os.path.dirname(_HERE)


class BeaverProcessorPlugin:
    """Toolbar/menu action that opens the Beaver processor map builder."""

    MENU = "&Beaver Processor"

    def __init__(self, iface):
        self.iface = iface
        self.action = None
        self.dialog = None

    # -- QGIS lifecycle ----------------------------------------------------------
    def initGui(self):
        icon_path = os.path.join(_PKG_ROOT, "icon.png")
        self.action = QAction(QIcon(icon_path), "Beaver Processor", self.iface.mainWindow())
        self.action.setToolTip("Build and export finished map products.")
        self.action.triggered.connect(self.run)
        self.iface.addToolBarIcon(self.action)
        self.iface.addPluginToMenu(self.MENU, self.action)

    def unload(self):
        if self.action is not None:
            self.iface.removePluginMenu(self.MENU, self.action)
            self.iface.removeToolBarIcon(self.action)
            self.action = None
        if self.dialog is not None:
            self.dialog.close()
            self.dialog = None

    # -- Action ---------------------------------------------------------------------
    def run(self):
        if self.dialog is not None and self.dialog.isVisible():
            self.dialog.raise_()
            self.dialog.activateWindow()
            return

        # Import lazily so plugin load stays instant and any import error
        # surfaces here rather than breaking QGIS startup.
        from .gui_generator import GUI_class

        self.dialog = QDialog(self.iface.mainWindow())
        self.dialog.setWindowTitle("Beaver processor")
        layout = QVBoxLayout(self.dialog)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(GUI_class())
        self.dialog.resize(1550, 900)
        self.dialog.show()
