from typing import Optional

from keycloak import KeycloakOpenID, KeycloakAdmin, KeycloakOpenIDConnection

from core.environment import Environment


class Keycloak:
    client: Optional[KeycloakOpenID] = None
    admin: Optional[KeycloakAdmin] = None

    url: Optional[str] = None
    client_id: Optional[str] = None
    realm: Optional[str] = None
    __client_secret: Optional[str] = None

    @classmethod
    def init(cls):
        cls.url = Environment.get("KEYCLOAK_URL", str)
        cls.client_id = Environment.get("KEYCLOAK_CLIENT_ID", str)
        cls.realm = Environment.get("KEYCLOAK_REALM", str)
        cls.__client_secret = Environment.get("KEYCLOAK_CLIENT_SECRET", str)

        cls.client = KeycloakOpenID(
            server_url=cls.url,
            client_id=cls.client_id,
            realm_name=cls.realm,
            client_secret_key=cls.__client_secret,
        )
        connection = KeycloakOpenIDConnection(
            server_url=cls.url,
            client_id=cls.client_id,
            realm_name=cls.realm,
            client_secret_key=cls.__client_secret,
        )
        cls.admin = KeycloakAdmin(connection=connection)
