# standard
from __future__ import annotations

from pathlib import Path
from typing import TYPE_CHECKING, Optional

# PyQGIS
from qgis.PyQt import uic
from qgis.PyQt.QtCore import pyqtSignal
from qgis.PyQt.QtGui import QIcon

# Project
from oslandia.__about__ import DIR_PLUGIN_ROOT
from oslandia.custom_exceptions import UnavailableUserError
from oslandia.gui.onboarding.wdg_base_page import WidgetPageBase
from oslandia.helpdesk.user import UserRequestManager


if TYPE_CHECKING:
    from qgis.PyQt.QtWidgets import QWidget


class CustomerPage(WidgetPageBase):
    is_customer_signal = pyqtSignal(bool)

    def __init__(self, parent: Optional[QWidget] = None):
        """Page that asks whether the user is already a customer or not.

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

        self.btn_customer_no.setIcon(
            QIcon(str(DIR_PLUGIN_ROOT / "resources/images/hourglass.svg"))
        )
        self.btn_customer_yes.setIcon(
            QIcon(str(DIR_PLUGIN_ROOT / "resources/images/checked.svg"))
        )

        # Connect buttons
        self.btn_customer_no.clicked.connect(self._on_no_clicked)
        self.btn_customer_yes.clicked.connect(self._on_yes_clicked)

    def _on_no_clicked(self) -> None:
        """Handle the case where the user is not a customer."""
        self.is_customer_signal.emit(False)
        self.next_page_signal.emit(
            3
        )  # Skip 3 pages (authentication + logged_in + customer features)

    def _on_yes_clicked(self) -> None:
        """Handle the case where the user is a customer."""
        self.is_customer_signal.emit(True)
        if self._check_if_user_is_connected:
            self.next_page_signal.emit(
                1
            )  # Skip authentication and go to user info page
        else:
            self.next_page_signal.emit(0)  # Go to authentication page

    @property
    def _check_if_user_is_connected(self) -> bool:
        """Check whether the user is already connected.

        :return: True if the user is connected, False otherwise
        :rtype: bool
        """
        try:
            manager = UserRequestManager()
            user = manager.get_current_user()
            if user:
                return True
        except UnavailableUserError:
            return False
