#! python3  # noqa: E265

"""
    Plugin settings form integrated into QGIS 'Options' menu.
"""
import os

# standard
from functools import partial
from pathlib import Path

import requests
from qgis.core import QgsSettings

# PyQGIS
from qgis.gui import QgsOptionsPageWidget, QgsOptionsWidgetFactory
from qgis.PyQt import uic
from qgis.PyQt.Qt import QUrl
from qgis.PyQt.QtGui import QDesktopServices, QIcon

# project
from openlog.__about__ import (
    DIR_PLUGIN_ROOT,
    __title__,
    __uri_documentation__,
    __uri_homepage__,
    __uri_tracker__,
    __version__,
)
from openlog.gui.extensions_handler import ExtensionsHandler
from openlog.gui.welcome.welcome import WelcomeScreen
from openlog.toolbelt import PlgLogger, PlgOptionsManager
from openlog.toolbelt.preferences import PlgSettingsStructure

# ############################################################################
# ########## Globals ###############
# ##################################


# ############################################################################
# ########## Classes ###############
# ##################################


class ConfigOptionsPage(QgsOptionsPageWidget):
    """Settings form embedded into QGIS 'options' menu."""

    def __init__(self, parent):
        super().__init__(parent)
        self.log = PlgLogger().log
        self.plg_settings = PlgOptionsManager()
        uic.loadUi(os.path.join(os.path.dirname(__file__), "dlg_settings.ui"), self)
        self.setObjectName("mOptionsPage{}".format(__title__))

        # header
        self.lbl_title.setText(f"{__title__} - Version {__version__}")

        # customization
        self.btn_help.setIcon(QIcon(":/images/themes/default/mActionHelpContents.svg"))
        self.btn_help.pressed.connect(
            partial(QDesktopServices.openUrl, QUrl(__uri_documentation__))
        )

        self.btn_report.setIcon(
            QIcon(":images/themes/default/console/iconSyntaxErrorConsole.svg")
        )
        self.btn_report.pressed.connect(
            partial(QDesktopServices.openUrl, QUrl(__uri_tracker__))
        )

        self.btn_newsletter.setIcon(
            QIcon(str(DIR_PLUGIN_ROOT) + "/resources/images/newsletter-svgrepo-com.svg")
        )
        self.btn_newsletter.pressed.connect(self.open_splash)

        self.reset_btn.setIcon(
            QIcon(":/images/themes/default/propertyicons/settings.svg")
        )
        self.reset_btn.pressed.connect(self._reset_openlog_settings)

        # load previously saved settings
        self.load_settings()

        # premium
        self.premium_handler = ExtensionsHandler(self)

    def _reset_openlog_settings(self) -> None:
        """
        Reset user settings (stored in QGIS3.ini file).
        """
        settings = QgsSettings()
        settings.beginGroup(__title__)
        settings.clear()

    def open_splash(self):
        ws = WelcomeScreen()
        ws.exec()

    def apply(self):
        """Called to permanently apply the settings shown in the options page (e.g. \
        save them to QgsSettings objects). This is usually called when the options \
        dialog is accepted."""
        new_settings = PlgSettingsStructure(
            # global
            debug_mode=self.opt_debug.isChecked(),
            version=__version__,
            remember=self.rmb_me.isChecked(),
            auto_login=self.autologin.isChecked(),
        )

        # dump new settings into QgsSettings
        self.plg_settings.save_from_object(new_settings)

        if __debug__:
            self.log(
                message="DEBUG - Settings successfully saved.",
                log_level=4,
            )

    def load_settings(self):
        """Load options from QgsSettings into UI form."""
        settings = self.plg_settings.get_plg_settings()

        # global
        self.opt_debug.setChecked(settings.debug_mode)
        self.lbl_version_saved_value.setText(settings.version)
        self.rmb_me.setChecked(settings.remember)
        self.autologin.setChecked(settings.auto_login)


class PlgOptionsFactory(QgsOptionsWidgetFactory):
    """Factory for options widget."""

    def __init__(self):
        super().__init__()

    def icon(self) -> QIcon:
        return QIcon(str(DIR_PLUGIN_ROOT / "resources/images/logo.png"))

    def createWidget(self, parent) -> ConfigOptionsPage:
        return ConfigOptionsPage(parent)

    def title(self) -> str:
        return __title__
