# -*- coding: utf-8 -*-
"""
BIG Downloader Toolbox Plugin
"""

from qgis.core import QgsApplication, QgsMessageLog, Qgis
from qgis.PyQt.QtCore import QSettings, QTranslator, qVersion, QCoreApplication
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QMenu, QMessageBox

import os.path
import processing

class BIGDownloaderToolboxPlugin:
    """Main plugin class"""
    
    def __init__(self, iface):
        self.iface = iface
        self.provider = None
        self.menu_actions = []
        self.toolbar = None
        self.plugin_dir = os.path.dirname(__file__)

    def initGui(self):
        """Initialize GUI"""
        try:
            # 1. Register Provider
            from .big_downloader_toolbox_provider import BIGDownloaderToolboxProvider
            self.provider = BIGDownloaderToolboxProvider()
            QgsApplication.processingRegistry().addProvider(self.provider)
            
            # 3. Setup Menus
            # Use pluginMenu() to put it under "Plugins"
            self.main_menu = QMenu("BIG Downloader Toolbox", self.iface.mainWindow())
            
            # Fix: Add icon to main menu
            # Use the global icon.png to match Processing Toolbox and About
            icon_menu = os.path.join(self.plugin_dir, 'icon.png')
            self.main_menu.setIcon(QIcon(icon_menu))
            
            self.iface.pluginMenu().addMenu(self.main_menu)
            
            # 3. Setup Toolbar
            self.toolbar = self.iface.addToolBar("BIG Downloader")
            self.toolbar.setObjectName("BIGDownloaderToolbar")
            
            # 4. Add Actions
            icon_login = os.path.join(self.plugin_dir, 'images', 'icon_login.png')
            icon_demnas = os.path.join(self.plugin_dir, 'images', 'icon_demnas.png')
            icon_rbi = os.path.join(self.plugin_dir, 'images', 'icon_rbi.png')
            icon_batnas = os.path.join(self.plugin_dir, 'images', 'icon_batnas.png')
            icon_about = os.path.join(self.plugin_dir, 'icon.png') # Use main icon for about
            
            # Fallback if specific icons missing
            if not os.path.exists(icon_login): icon_login = os.path.join(self.plugin_dir, 'icon.png')
            if not os.path.exists(icon_demnas): icon_demnas = os.path.join(self.plugin_dir, 'icon.png')
            if not os.path.exists(icon_rbi): icon_rbi = os.path.join(self.plugin_dir, 'icon.png')
            if not os.path.exists(icon_batnas): icon_batnas = os.path.join(self.plugin_dir, 'icon.png')

            # Action: Login
            self.add_action(
                icon_login,
                "1. Login INA-Geoportal",
                self.run_login,
                "Login for Token"
            )
            
            self.main_menu.addSeparator()

            # Action: Download DEMNAS
            self.add_action(
                icon_demnas,
                "2. Download DEMNAS (Mosaic)",
                self.run_demnas,
                "Download DEMNAS"
            )
            
            # Action: Download RBI
            self.add_action(
                icon_rbi,
                "3. Download RBI",
                self.run_rbi,
                "Download RBI"
            )
            
            # Action: Download BATNAS
            self.add_action(
                icon_batnas,
                "4. Download BATNAS",
                self.run_batnas,
                "Download BATNAS"
            )
            
            self.main_menu.addSeparator()
            
            # Action: About
            self.add_action_menu_only(
                icon_about, 
                "About",
                self.run_about,
                "About Plugin"
            )

        except Exception as e:
            QgsMessageLog.logMessage(
                f'Error loading BIG Downloader GUI: {str(e)}',
                'BIG Downloader',
                Qgis.Critical
            )

    def add_action(self, icon_path, text, callback, object_name):
        icon = QIcon(icon_path)
        action = QAction(icon, text, self.iface.mainWindow())
        action.setObjectName(object_name)
        action.triggered.connect(callback)
        
        self.main_menu.addAction(action)
        self.toolbar.addAction(action)
        self.menu_actions.append(action)

    def add_action_menu_only(self, icon_path, text, callback, object_name):
        icon = QIcon(icon_path)
        action = QAction(icon, text, self.iface.mainWindow())
        action.setObjectName(object_name)
        action.triggered.connect(callback)
        
        self.main_menu.addAction(action)
        self.menu_actions.append(action)

    def run_login(self):
        processing.execAlgorithmDialog("big_downloader:login_demnas")

    def run_demnas(self):
        processing.execAlgorithmDialog("big_downloader:download_demnas_pro")

    def run_rbi(self):
        processing.execAlgorithmDialog("big_downloader:download_rbi_tool_pro")
        
    def run_batnas(self):
        processing.execAlgorithmDialog("big_downloader:download_batnas")
        
    def run_about(self):
        QMessageBox.information(
            self.iface.mainWindow(),
            "About BIG Downloader",
            "BIG Downloader Tools v3.1.0\n\n"
            "Plugin untuk mengunduh data DEMNAS, RBI, dan BATNAS dari INA-Geoportal.\n"
            "Dikembangkan oleh: Ahza Studio\n\n"
            "Kontak: +62 822-5476-0769"
        )

    def unload(self):
        """Unload plugin"""
        # Remove Provider
        if self.provider:
            QgsApplication.processingRegistry().removeProvider(self.provider)
            self.provider = None
            
        # Remove Menu (Important: remove from plugin menu)
        if self.main_menu:
            self.iface.pluginMenu().removeAction(self.main_menu.menuAction())
            self.main_menu.deleteLater()
            
        # Remove Toolbar
        if self.toolbar:
            del self.toolbar
            
        # Remove Actions
        for action in self.menu_actions:
            self.iface.removePluginMenu('&BIG Downloader', action)
            self.iface.removeToolBarIcon(action)