import os
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QToolBar
from qgis.core import QgsApplication
from .mosaic_dialog import MosaicDialog
from .mosaic_provider import MosaicProvider

class MosaicTool:
    def __init__(self, iface):
        self.iface = iface
        self.plugin_dir = os.path.dirname(__file__)
        
        # Initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n', f'mosaic_tool_{locale}.qm')
        
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)
        
        self.actions = []
        self.menu = self.tr('MAS Raster Processing')
        
        # Initialize toolbar reference
        self.toolbar = None
        self.toolbar_name = 'MASRasterProcessingToolbar'
        
        # Store dialog and provider references
        self.dlg = None
        self.provider = None

    def tr(self, message):
        return QCoreApplication.translate('MosaicTool', message)

    def initGui(self):
        """Initialize the GUI"""
        # Use mosaic.png as icon
        icon_path = os.path.join(self.plugin_dir, 'mosaic.png')
        
        # Find or create the MAS Raster Processing toolbar
        self.toolbar = self.iface.mainWindow().findChild(QToolBar, self.toolbar_name)
        if not self.toolbar:
            self.toolbar = self.iface.addToolBar('MAS Raster Processing')
            self.toolbar.setObjectName(self.toolbar_name)
        
        # Create QIcon - use a default icon if mosaic.png doesn't exist
        if os.path.exists(icon_path):
            icon = QIcon(icon_path)
        else:
            # Create a simple default icon if mosaic.png is missing
            icon = self.iface.style().standardIcon(self.iface.style().SP_FileDialogDetailedView)
        
        self.action = QAction(
            icon,
            self.tr('Mosaic Tool'),
            self.iface.mainWindow()
        )
        self.action.triggered.connect(self.run)
        self.action.setEnabled(True)
        self.action.setStatusTip(self.tr('Create advanced raster mosaics with compression options'))
        self.action.setWhatsThis(self.tr('Mosaic multiple raster bands with advanced spatial alignment and compression'))
        self.action.setObjectName('mosaic_tool_action')  # Set unique object name for cleanup
        
        # Add to Raster -> MAS Raster Processing menu
        self.iface.addPluginToRasterMenu(self.menu, self.action)
        
        # Add to toolbar (now self.toolbar is properly defined)
        self.toolbar.addAction(self.action)
        
        # Store action for cleanup
        self.actions.append(self.action)
        
        # Make sure toolbar is visible
        self.toolbar.setVisible(True)
        
        # Initialize processing provider for toolbox
        self.initProcessing()

    def initProcessing(self):
        """Initialize processing provider"""
        try:
            self.provider = MosaicProvider()
            QgsApplication.processingRegistry().addProvider(self.provider)
            print(f"Provider '{self.provider.name()}' registered successfully")
        except Exception as e:
            print(f"Error registering provider: {str(e)}")

    def unload(self):
        """Remove the plugin menu item and icon from QGIS GUI"""
        # Remove from menu
        for action in self.actions:
            self.iface.removePluginRasterMenu(self.menu, action)
        
        # Remove actions from toolbar
        if self.toolbar:
            for action in self.actions:
                self.toolbar.removeAction(action)
            
            # Check if toolbar is empty and remove it if so
            if len(self.toolbar.actions()) == 0:
                self.iface.mainWindow().removeToolBar(self.toolbar)
                self.toolbar = None
        
        # Clean up actions
        for action in self.actions:
            action.deleteLater()
        self.actions.clear()
        
        # Unregister processing provider
        if self.provider:
            try:
                QgsApplication.processingRegistry().removeProvider(self.provider)
                print(f"Provider '{self.provider.name()}' unregistered successfully")
            except Exception as e:
                print(f"Error unregistering provider: {str(e)}")
            self.provider = None

    def run(self):
        """Run method that opens the dialog"""
        if self.dlg is None:
            self.dlg = MosaicDialog(self.iface)
        
        # Show the dialog
        self.dlg.show()
        result = self.dlg.exec_()
        
        # Reset dialog for next use
        if result:
            self.dlg = None
