import os

from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction

from .main_dialog import MainDialog


class CadastreZipEditor:
    def __init__(self, iface):
        self.iface = iface
        self.plugin_dir = os.path.dirname(__file__)
        self.action = None
        self.toolbar = None
        self.dialog = None

    def initGui(self):
        icon_path = os.path.join(self.plugin_dir, "icon.png")

        self.toolbar = self.iface.addToolBar("Cadastre ZIP Editor")
        self.toolbar.setObjectName("CadastreZipEditorToolbar")

        self.action = QAction(
            QIcon(icon_path),
            "Cadastre ZIP Editor",
            self.iface.mainWindow()
        )
        self.action.setObjectName("CadastreZipEditorAction")
        self.action.setToolTip("Cadastre ZIP Editor")
        self.action.triggered.connect(self.run)

        self.toolbar.addAction(self.action)
        self.iface.addPluginToMenu("Cadastre ZIP Editor", self.action)

    def unload(self):
        if self.action:
            self.iface.removePluginMenu("Cadastre ZIP Editor", self.action)

        if self.toolbar and self.action:
            self.toolbar.removeAction(self.action)

        if self.action:
            try:
                self.action.deleteLater()
            except Exception:
                pass

        self.action = None
        self.toolbar = None

    def run(self):
        if self.dialog is None:
            self.dialog = MainDialog(self.plugin_dir)
        self.dialog.show()
        self.dialog.raise_()
        self.dialog.activateWindow()