# python3  # noqa: E265

"""
    Main plugin module.
"""

import os

from qgis.core import Qgis, QgsApplication, QgsProject
from qgis.gui import QgisInterface
from qgis.PyQt.QtCore import QCoreApplication
from qgis.PyQt.QtGui import QIcon

# from PyQt5 import QtWidgets
from qgis.PyQt.QtWidgets import QAction, QMenu, QToolBar, QToolButton

from plui_versionning.__about__ import __title__
from plui_versionning.gui.dlg_database import DatabaseSettings
from plui_versionning.gui.dlg_import_projet import ImportProjetDialog
from plui_versionning.gui.dlg_nouvelle_procedure import NouvelleProcedureDialog
from plui_versionning.gui.dlg_plui_selector import PLUiWizard
from plui_versionning.gui.dlg_settings import PlgOptionsFactory
from plui_versionning.gui.wdg_dashboard import PLUiDashboard
from plui_versionning.toolbelt import PlgLogger, PlgOptionsManager, PlgTranslator

# PyQGIS


# ##################################
#               Classes
# ##################################q


def resource(name):
    """Return name with prepended current directory path)"""
    return os.path.join(os.path.dirname(__file__), name)


class PluiVersionningPlugin:
    def __init__(self, iface: QgisInterface):
        """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.log = PlgLogger().log

        # translation
        plg_translation_mngr = PlgTranslator()
        translator = plg_translation_mngr.get_translator()
        if translator:
            QCoreApplication.installTranslator(translator)
        self.tr = plg_translation_mngr.tr

        # Get Plugin Settings
        self.plg_settings = PlgOptionsManager()

    def initGui(self):
        """Set up plugin UI elements."""

        # settings page within the QGIS preferences menu
        self.options_factory = PlgOptionsFactory()
        self.iface.registerOptionsWidgetFactory(self.options_factory)
        self.action_settings = QAction(
            QgsApplication.getThemeIcon("console/iconSettingsConsole.svg"),
            self.tr("Options"),
            self.iface.mainWindow(),
        )
        self.action_settings.triggered.connect(
            lambda: self.iface.showOptionsDialog(currentPage=f"mOptionsPage{__title__}")
        )

        self.action_help = QAction(
            icon=QIcon(QgsApplication.iconPath("console/iconHelpConsole.svg")),
            text=self.tr("Help"),
        )
        # self.action_help.triggered.connect(lambda: openUrl())

        self.action_database_settings = QAction(
            icon=QIcon(QgsApplication.iconPath("dbmanager.svg")),
            text=self.tr("Configuration base de données"),
        )
        self.action_database_settings.triggered.connect(self.set_database_settings)

        self.action_plui_selection = QAction(
            icon=QIcon(QgsApplication.iconPath("mActionAddLayer.svg")),
            text=self.tr("Choix de la version à importer dans le projet"),
        )
        self.action_plui_selection.triggered.connect(self.select_PLUi)

        self.action_plui_new_procedure = QAction(
            icon=QIcon(QgsApplication.iconPath("mAction.svg")),
            text=self.tr("Initier une nouvelle procédure"),
        )
        self.action_plui_new_procedure.triggered.connect(self.new_procedure)

        self.action_plui_import_projet = QAction(
            icon=QIcon(QgsApplication.iconPath("mAction.svg")),
            text=self.tr("Importer un projet"),
        )
        self.action_plui_import_projet.triggered.connect(self.import_projet)

        self.action_plui_dashboard = QAction(
            icon=QIcon(QgsApplication.iconPath("mIconListView.svg")),
            text=self.tr("Tableau de bord"),
        )
        self.action_plui_dashboard.triggered.connect(self.dashboard)
        # -- Menu
        self.iface.addPluginToMenu(__title__, self.action_database_settings)
        self.iface.addPluginToMenu(__title__, self.action_plui_selection)
        self.iface.addPluginToMenu(__title__, self.action_plui_new_procedure)
        self.iface.addPluginToMenu(__title__, self.action_plui_import_projet)
        self.iface.addPluginToMenu(__title__, self.action_plui_dashboard)
        self.iface.addPluginToMenu(__title__, self.iface.actionPluginListSeparator())
        self.iface.addPluginToMenu(__title__, self.action_settings)

        self.toolbar = QToolBar("Plui")
        self.toolbar.addAction(self.action_database_settings)
        self.toolbar.addAction(self.action_plui_selection)
        # Create button for PLUi actions
        button = QToolButton()
        button.setMenu(QMenu())
        button.setPopupMode(QToolButton.MenuButtonPopup)
        button.setDefaultAction(self.action_plui_new_procedure)
        button.menu().addAction(self.action_plui_new_procedure)
        button.menu().addAction(self.action_plui_import_projet)
        self.toolbar.addWidget(button)
        self.toolbar.addAction(self.action_plui_dashboard)
        self.iface.addToolBar(self.toolbar)

    def unload(self):
        """Cleans up when plugin is disabled/uninstalled."""
        # -- Clean up menu
        self.iface.removePluginMenu(__title__, self.action_settings)
        self.iface.removePluginMenu(__title__, self.action_database_settings)
        self.iface.removePluginMenu(__title__, self.action_plui_selection)
        self.iface.removePluginMenu(__title__, self.action_plui_new_procedure)
        self.iface.removePluginMenu(__title__, self.action_plui_import_projet)
        self.iface.removePluginMenu(__title__, self.action_plui_dashboard)

        # -- Clean up preferences panel in QGIS settings
        self.iface.unregisterOptionsWidgetFactory(self.options_factory)

        # remove actions
        del self.action_settings
        del self.action_database_settings
        del self.action_plui_selection
        del self.action_plui_new_procedure
        del self.action_plui_import_projet
        del self.action_plui_dashboard

        # remove toolbar :
        self.toolbar.deleteLater()

    def run(self):
        """Main process.

        :raises Exception: if there is no item in the feed
        """
        try:
            self.log(
                message=self.tr(
                    text="Everything ran OK.",
                    context="PluiVersionningPlugin",
                ),
                log_level=Qgis.Success,
                push=False,
            )
        except Exception as err:
            self.log(
                message=self.tr(
                    text=f"Houston, we've got a problem: {err}",
                    context="PluiVersionningPlugin",
                ),
                log_level=Qgis.Critical,
                push=True,
            )

    def lines(self):
        with self.connect() as con:
            cur = con.cursor()
            cur.execute("select id from api.line_name")

    def dashboard(self):
        current_settings = self.plg_settings.get_plg_settings()
        if current_settings.is_db_connection_valid:
            self.log(
                message=self.tr(
                    text="Tableau de bord", context="PluiVersionningPlugin"
                ),
                log_level=Qgis.Info,
                push=True,
            )
            wdg_plui_dashboard = PLUiDashboard()
            wdg_plui_dashboard.show()
        else:
            self.log(
                message=self.tr(
                    text="La connexion à la base de données n'a pas été configurée.",
                    context="PluiVersionningPlugin",
                ),
                log_level=Qgis.Warning,
                push=True,
            )
            self.set_database_settings()

    def new_procedure(self):
        self.log(
            message=self.tr(
                text="Initier une nouvelle procédure", context="PluiVersionningPlugin"
            ),
            log_level=Qgis.Info,
            push=True,
        )
        dlg_nouvelle_procedure = NouvelleProcedureDialog(self.iface.mainWindow())
        dlg_nouvelle_procedure.exec()

    def import_projet(self):
        self.log(
            message=self.tr(text="Importer un projet", context="PluiVersionningPlugin"),
            log_level=Qgis.Info,
            push=True,
        )
        dlg_nouveau_projet = ImportProjetDialog(self.iface.mainWindow())
        dlg_nouveau_projet.exec()

    def select_PLUi(self):
        self.project = QgsProject.instance()
        current_settings = self.plg_settings.get_plg_settings()
        if current_settings.is_db_connection_valid:
            dlg_plui_selector = PLUiWizard(self.iface.mainWindow())
            dlg_plui_selector.exec()
        else:
            self.log(
                message=self.tr(
                    text="La connexion à la base de données n'a pas été configurée.",
                    context="PluiVersionningPlugin",
                ),
                log_level=Qgis.Warning,
                push=True,
            )
            self.set_database_settings()

    def set_database_settings(self):
        dlg_db_settings = DatabaseSettings(self.iface.mainWindow())
        dlg_db_settings.exec()
