
#################################################
# HolAdo (Holistic Automation do)
#
# (C) Copyright 2021-2025 by Eric Klumpp
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

# The Software is provided “as is”, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the Software.
#################################################

import logging
from datetime import timedelta, datetime

from holado.common.handlers.undefined import default
from holado_security.token.token_manager import TokenManager, ExpiringTokenManager
from holado_security.tools.keycloak.keycloak_client import KeycloakClient


logger = logging.getLogger(__name__)

class KeycloakTokenManager(ExpiringTokenManager):
    """
    Manage Keycloak tokens.
    Note: In this implementation, 'request_kwargs' argument of method get_token has to be arguments of KeycloakClient.get_token.
          If another signature is needed, it can be done by overriding methods 'get_token', 'request_token' and 'request_refresh'.
    """

    def __init__(self):
        super().__init__(with_refresh=True)

    def get_token_type(self, *, uid, request_kwargs=None, needed_time_s=default):
        return super().get_token(uid=uid, request_kwargs=request_kwargs, needed_time_s=needed_time_s)["token_type"]

    def get_access_token(self, *, uid, request_kwargs=None, needed_time_s=default):
        return super().get_token(uid=uid, request_kwargs=request_kwargs, needed_time_s=needed_time_s)["access_token"]

    def get_refresh_token(self, *, uid):
        return super().get_token(uid=uid)["refresh_token"]

    def get_expires_in(self, *, uid):
        return super().get_token(uid=uid)["expires_in"]

    def ensure_token_is_valid(self, *, uid, request_kwargs=None, needed_time_s=default):
        needed_time_s = needed_time_s if needed_time_s is not default else self.default_needed_time_s

        # Ensure needed_time_s is at most expires_in/2 to optimize the number of refresh
        if self.has_token(uid=uid):
            expires_in = self.get_expires_in(uid=uid)
            if expires_in // 2 < needed_time_s:
                needed_time_s = expires_in // 2
        super().ensure_token_is_valid(uid=uid, request_kwargs=request_kwargs, needed_time_s=needed_time_s)

    def request_token(self, *, keycloak_client, **request_kwargs):
        return keycloak_client.get_token(**request_kwargs)

    def request_refresh(self, *, uid, keycloak_client, **request_kwargs):
        kwargs = {k:request_kwargs[k] for k in request_kwargs if k in ('realm_name', 'client_id', 'client_secret')}
        return keycloak_client.get_token_by_grant_type_refresh_token(refresh_token=self.get_refresh_token(uid=uid), **kwargs)

    def _new_token_info(self, *, token, request_kwargs=None):
        res = super()._new_token_info(token=token, request_kwargs=request_kwargs)
        res.expiration_date = res.creation_date + timedelta(seconds=token["expires_in"])
        res.refresh_expiration_date = res.creation_date + timedelta(seconds=token["refresh_expires_in"])
        return res

    def logout(self, *, uid, keycloak_client, **kwargs):
        """ Logout from Keycloak with token of given UID"""
        # Logout from keycloak
        keycloak_client.logout(refresh_token=self.get_refresh_token(uid=uid), **kwargs)

        # Remove stored token
        self.delete_token(uid=uid)


