from oslandia.custom_exceptions import UnavailableUserError
from oslandia.helpdesk.user import UserRequestManager
from oslandia.toolbelt import PlgOptionsManager


def check_connection(qgis_auth_id: str) -> bool:
    """Check if connection is valid for a qgis authentication id.

    :param qgis_auth_id: qgis authentication id to use
    :type qgis_auth_id: str

    :return: True if connection is valid for qgis_auth_id, False otherwise
    :rtype: bool
    """

    res = True

    # Check connection to API by getting token user information
    try:
        manager = UserRequestManager()
        manager.plg_settings.authentification_config_id = qgis_auth_id
        manager.get_current_user()
    except UnavailableUserError:
        res = False

    return res


def check_connection_for_current_settings() -> bool:
    """Check if connect is valid for current settings

    :return: True if connection is valid for current settings, False otherwise
    :rtype: bool
    """
    auth_id = PlgOptionsManager().get_plg_settings().authentification_config_id
    if not auth_id:
        return False
    return check_connection(auth_id)
