# -*- coding: utf-8 -*-
import os
from qgis.PyQt.QtWidgets import QAction
from qgis.PyQt.QtGui import QIcon
from qgis.core import QgsMessageLog, Qgis

from .dialog import ViewshedCalculatorDialog


class ViewshedCalculatorPlugin:
    """QGIS plugin for calculating viewshed from DSM."""

    def __init__(self, iface):
        """Initialize the plugin."""
        self.iface = iface
        self.action = None
        self.dialog = None

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        icon_path = os.path.join(os.path.dirname(__file__), 'icons', 'icon.png')
        if not os.path.exists(icon_path):
            icon_path = None

        self.action = QAction(u'Viewshed Calculator', self.iface.mainWindow())
        if icon_path:
            self.action.setIcon(QIcon(icon_path))
        self.action.triggered.connect(self.run)

        # Add to menu
        self.iface.addPluginToMenu(u'&Analysis', self.action)
        # Add to toolbar
        self.iface.addToolBarIcon(self.action)

        QgsMessageLog.logMessage(
            'Viewshed Calculator plugin loaded successfully',
            'Viewshed Calculator',
            Qgis.Info
        )

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        self.iface.removePluginMenu(u'&Analysis', self.action)
        self.iface.removeToolBarIcon(self.action)

    def run(self):
        """Run the plugin dialog."""
        if self.dialog is None:
            self.dialog = ViewshedCalculatorDialog(self.iface)
        self.dialog.show()
