# -*- coding: utf-8 -*-
"""
/***************************************************************************
 DualProfileViewer
                                 A QGIS plugin
 Archaeological dual profile analysis with vector export
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2024-01-01
        git sha              : $Format:%H$
        copyright            : (C) 2024
        email                : your.email@example.com
 ***************************************************************************/
"""

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 QgsProject
import os.path

# Import the docked viewer and 3D viewer
from .dual_profile_dock import DualProfileDock
from .advanced_3d_viewer import Advanced3DViewer


class DualProfileViewer:
    """Main plugin implementation."""

    def __init__(self, iface):
        """Constructor.
        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        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',
            'DualProfileViewer_{}.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 = '&Dual Profile Viewer'
        self.toolbar = None
        self.dialog = None
        self.dock_widget = None
        self.viewer_3d = None


    def tr(self, message):
        """Get the translation for a string using Qt translation API."""
        return QCoreApplication.translate('DualProfileViewer', 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):
        """Add a toolbar icon to the toolbar."""

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

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

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

        if add_to_toolbar:
            if self.toolbar is None:
                self.toolbar = self.iface.addToolBar('Dual Profile Viewer')
            self.toolbar.addAction(action)

        if add_to_menu:
            self.iface.addPluginToRasterMenu(
                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.png')
        #icon_path2 = os.path.join(self.plugin_dir, 'image.png')
        
        # Add main viewer action
        self.add_action(
            icon_path,
            text=self.tr('Dual Profile Viewer'),
            callback=self.run,
            parent=self.iface.mainWindow(),
            status_tip=self.tr('Create dual elevation profiles from DEM/DTM'),
            whats_this=self.tr('Archaeological dual profile analysis tool'))
        
        # Add 3D viewer action
        # self.add_action(
        #     icon_path2,
        #     text=self.tr('Advanced 3D Profile Viewer'),
        #     callback=self.run_3d_viewer,
        #     parent=self.iface.mainWindow(),
        #     status_tip=self.tr('Advanced 3D visualization of profiles'),
        #     whats_this=self.tr('View profiles in 3D with advanced features'))

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginRasterMenu(
                self.menu,
                action)
            self.iface.removeToolBarIcon(action)
        
        if self.toolbar:
            del self.toolbar

    def run(self):
        """Run method that performs all the real work"""
        # Create dock widget if it doesn't exist
        if not self.dock_widget:
            self.dock_widget = DualProfileDock(self.iface, parent=self.iface.mainWindow())
            self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock_widget)
            self.dialog = self.dock_widget.get_profile_viewer()
        
        # Show the dock widget
        self.dock_widget.show()
        self.dock_widget.raise_()
    
    def run_3d_viewer(self):
        """Open the advanced 3D viewer"""
        if not self.viewer_3d:
            self.viewer_3d = Advanced3DViewer(parent=self.iface.mainWindow())
        
        # Get profile data from main dialog if available
        if self.dialog and hasattr(self.dialog, 'profile_data_list') and self.dialog.profile_data_list:
            # Pass the profile data list directly
            self.viewer_3d.load_profiles(self.dialog.profile_data_list)
        elif self.dialog and hasattr(self.dialog, 'profile_data') and self.dialog.profile_data:
            # Convert single profile data to list format expected by 3D viewer
            profile_list = []
            profile_data = self.dialog.profile_data
            
            # Check if we have the correct structure
            if 'profile1' in profile_data:
                profile_list.append(profile_data['profile1'])
            if 'profile2' in profile_data:
                profile_list.append(profile_data['profile2'])
                
            if profile_list:
                self.viewer_3d.load_profiles(profile_list)
        
        self.viewer_3d.show()
        self.viewer_3d.exec_()