import os
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, Qt
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QToolBar
from qgis.core import QgsApplication

class CRSFinderPlugin:
    """QGIS Plugin Implementation for CRS Finder."""

    def __init__(self, iface):
        """Constructor.
        
        Args:
            iface (QgsInterface): A reference to the QgisInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        
        # Initialize plugin directory
        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',
            'CRSFinder_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&MAS Vector Processing')
        self.toolbar = None
        self.dockwidget = None
        self.toggle_action = None
        
        # Plugin state
        self.pluginIsActive = False

    def tr(self, message):
        """Get the translation for a string using Qt translation API.
        
        Args:
            message (str): String for translation.
            
        Returns:
            str: Translated string.
        """
        return QCoreApplication.translate('CRSFinderPlugin', message)

    def add_action(self, icon_path, text, callback, enabled_flag=True,
                   add_to_menu=True, add_to_toolbar=True, status_tip=None,
                   whats_this=None, parent=None, checkable=False):
        """Add a toolbar icon to the toolbar.
        
        Args:
            icon_path (str): Path to the icon for this action.
            text (str): Text that should be shown in menu items for this action.
            callback (function): Function to be called when the action is triggered.
            enabled_flag (bool): A flag indicating if the action should be enabled
                by default. Defaults to True.
            add_to_menu (bool): Flag indicating whether the action should also
                be added to the menu. Defaults to True.
            add_to_toolbar (bool): Flag indicating whether the action should also
                be added to the toolbar. Defaults to True.
            status_tip (str): Optional text to show in a popup when mouse pointer
                hovers over the action.
            whats_this (str): Optional text to show in the status bar when the
                mouse pointer hovers over the action.
            parent: Parent widget for the new action. Defaults None.
            checkable (bool): Whether the action should be checkable.
                
        Returns:
            QAction: The action that was created.
        """
        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)
        action.setCheckable(checkable)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            # Check if the common toolbar already exists, if not create it
            tb = self.iface.mainWindow().findChild(QToolBar, 'MASVectorProcessingToolbar')
            if not tb:
                tb = self.iface.addToolBar('MAS Vector Processing')
                tb.setObjectName('MASVectorProcessingToolbar')
            self.toolbar = tb
            self.toolbar.addAction(action)

        if add_to_menu:
            self.iface.addPluginToVectorMenu(self.menu, action)

        self.actions.append(action)
        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        
        icon_path = os.path.join(self.plugin_dir, 'icon_crs_finder.png')
        
        # Create the toggle action
        self.toggle_action = self.add_action(
            icon_path,
            text=self.tr(u'CRS Finder'),
            callback=self.toggle_dockwidget,
            status_tip=self.tr(u'Find and assign suitable CRS for layers'),
            whats_this=self.tr(u'Intelligent CRS finder and assignment tool'),
            parent=self.iface.mainWindow(),
            checkable=True)

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        
        # Close the dockwidget first
        if self.dockwidget:
            self.dockwidget.close()
            self.iface.removeDockWidget(self.dockwidget)
            self.dockwidget = None
        
        # Remove actions
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&MAS Vector Processing'),
                action)
            
            # Remove from toolbar if this plugin added the action
            if self.toolbar and action in self.toolbar.actions():
                self.toolbar.removeAction(action)

        # Check if toolbar is empty and remove it if no other plugins are using it
        if self.toolbar:
            remaining_actions = [a for a in self.toolbar.actions() if not a.isSeparator()]
            if len(remaining_actions) == 0:
                # Toolbar is empty, remove it
                self.iface.mainWindow().removeToolBar(self.toolbar)
                self.toolbar = None

        # Clean up references
        self.actions = []
        self.toggle_action = None
        self.pluginIsActive = False

    def toggle_dockwidget(self):
        """Toggle the visibility of the dockwidget"""
        
        if not self.pluginIsActive:
            self.pluginIsActive = True
            
            # Create the dockwidget if it doesn't exist
            if self.dockwidget is None:
                from .crs_finder_dockwidget import CRSFinderDockWidget
                self.dockwidget = CRSFinderDockWidget(self.iface)
                
                # Connect the closing signal to handle cleanup
                self.dockwidget.closingPlugin.connect(self.onClosePlugin)
                
                # Add to QGIS
                self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockwidget)
                
                # Link the toggle action to the dockwidget
                # This automatically handles the checked state of the toolbar button
                if hasattr(self.dockwidget, 'setToggleVisibilityAction'):
                    # Use QGIS-specific method if available
                    self.dockwidget.setToggleVisibilityAction(self.toggle_action)
                else:
                    # Fallback: manually connect visibility changes
                    self.dockwidget.visibilityChanged.connect(self.toggle_action.setChecked)
                
            # Show the dockwidget
            self.dockwidget.show()
            self.dockwidget.raise_()  # Bring to front
            self.toggle_action.setChecked(True)
            
        else:
            # Toggle visibility
            if self.dockwidget and self.dockwidget.isVisible():
                self.dockwidget.hide()
                self.toggle_action.setChecked(False)
            else:
                if self.dockwidget:
                    self.dockwidget.show()
                    self.dockwidget.raise_()
                    self.toggle_action.setChecked(True)

    def onClosePlugin(self):
        """Cleanup necessary items here when plugin dockwidget is closed"""
        
        # Update the toggle action state
        if self.toggle_action:
            self.toggle_action.setChecked(False)
        
        # Don't destroy the dockwidget, just hide it
        # This allows it to be reopened later
        if self.dockwidget:
            self.dockwidget.hide()
        
        # Keep pluginIsActive as True so the dockwidget can be reopened
        # Only set to False when plugin is completely unloaded

    def run(self):
        """Legacy run method for compatibility - delegates to toggle"""
        self.toggle_dockwidget()
