#! python3  # noqa: E265

"""Authentication dialog logic."""

# standard
from functools import partial
from pathlib import Path

# PyQGIS
from qgis.core import QgsApplication, QgsAuthManager
from qgis.PyQt import uic
from qgis.PyQt.QtCore import pyqtSignal
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QMessageBox, QWidget

# Plugin
from oslandia.__about__ import DIR_PLUGIN_ROOT
from oslandia.constants import UTM_CONTENT_PROFILE
from oslandia.custom_exceptions import UnavailableUserError
from oslandia.gui.stylesheet import DialogStyleSheet
from oslandia.helpdesk.user import UserRequestManager
from oslandia.toolbelt import PlgLogger, PlgOptionsManager
from oslandia.toolbelt.network_manager import open_url_in_browser


class UserDialog(DialogStyleSheet):
    # Define the custom signal this map tool will have
    # Always needs to be implemented as a class attributes like this
    user_disconnected = pyqtSignal()

    def __init__(self, parent: QWidget | None = None) -> None:
        """Dialog to display current user and change user if needed.

        :param parent: parent widget, defaults to None
        :type parent: QObject, optional
        """
        # init module and ui
        super().__init__(parent)
        uic.loadUi(Path(__file__).parent / f"{Path(__file__).stem}.ui", self)

        # toolbelt
        self.log = PlgLogger().log
        self.plg_settings_mngr = PlgOptionsManager()
        self.plg_settings = self.plg_settings_mngr.get_plg_settings()

        self.btn_disconnect_user.setIcon(
            QgsApplication.getThemeIcon("repositoryUnavailable.svg")
        )
        self.btn_disconnect_user.clicked.connect(self._disconnect_user)

        self.btn_open_gitlab.setIcon(
            QIcon(
                str(
                    DIR_PLUGIN_ROOT.joinpath(
                        "resources/images/oslandia_favicon_gitlab.svg"
                    )
                )
            )
        )

        self.update_user_widget()

        self.buttonBox.accepted.connect(self.accept)
        self.setModal(False)

    def update_user_widget(self) -> None:
        """Update user widget with current user"""
        try:
            manager = UserRequestManager()
            user = manager.get_current_user()
            self.wdg_user.set_user(user)
            self.btn_open_gitlab.clicked.connect(
                partial(
                    open_url_in_browser,
                    f"{self.plg_settings.gitlab_url_instance}{user.username}",
                    UTM_CONTENT_PROFILE,
                )
            )
            self.setWindowTitle(
                "Oslandia - " + self.tr("Logged in as {}".format(user.name))
            )
        except UnavailableUserError as exc:
            QMessageBox.information(
                self,
                self.tr("Error"),
                self.tr("Can't define current user : {}".format(exc)),
            )

    def _disconnect_user(self) -> None:
        """Display AuthenticationDialog to change connected user"""
        auth_manager: QgsAuthManager | None = QgsApplication.authManager()
        if isinstance(auth_manager, QgsAuthManager):
            auth_manager.removeAuthenticationConfig(
                self.plg_settings.authentification_config_id
            )
        self.plg_settings.authentification_config_id = None
        self.plg_settings_mngr.save_from_object(self.plg_settings)

        self.user_disconnected.emit()
        self.close()
