# -*- coding: utf-8 -*-
"""
/***************************************************************************
 ChineseBasemap
                                 A QGIS plugin
 This plugin provides multiple basemap datasource for China.
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2025-08-15
        copyright            : (C) 2025 by phoenix-gis
        email                : phoenixgis@sina.com
        website              : phoenix-gis.cn
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""


from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QToolBar

# Initialize Qt resources from file resources_rc.py
# Extend to load root directory.
import sys
import os.path
sys.path.append(os.path.dirname(__file__))
from .resources_rc import *

from .main.add_layer_dlg import AddLayerDlg
from .main.global_helper import GlobalHelper

class ChineseBasemap():
    """QGIS 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
        """
        # 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')
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'ChineseBasemap_{}.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 = GlobalHelper.tr(u'Chinese Resource')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

        self.maindlg = None
        self.toolbar = None

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/chinesebasemap/icon.png'

        # build custom toolbar
        toolbar = QToolBar(GlobalHelper.tr(u"Chinese Resource Toolbar"))
        toolbar.setToolTip(GlobalHelper.tr(u"Chinese Resource Toolbar"))
        self.iface.addToolBar(toolbar)

        self.add_action(
            icon_path,
            text=GlobalHelper.tr(u'Chinese Basemap'),
            callback=self.run,
            toolbar=toolbar,
            parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True
        self.toolbar = toolbar

    def add_action(
        self,
        icon_path,
        text,
        callback,
        toolbar,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):

        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 and toolbar is not None:
            toolbar.addAction(action)

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

        self.actions.append(action)

        return action

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        main_window = self.iface.mainWindow()
        for action in self.actions:
            self.iface.removePluginMenu(
                GlobalHelper.tr(u'Chinese Resource'),
                action)
            self.iface.removeToolBarIcon(action)
        if self.maindlg is not None:
            self.maindlg.unload()
        if self.toolbar is not None:
            main_window.removeToolBar(self.toolbar)
            self.toolbar.deleteLater()
        self.first_start = True

    def run(self):
        """Run method that performs all the real work"""

        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            self.maindlg = AddLayerDlg(self.iface)
            self.maindlg.setModal(True)

        # show the dialog
        self.maindlg.show()
        # Run the dialog event loop
        result = self.maindlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass
