import datetime
import os

import jwt
from dotenv import load_dotenv

from idcloud.environment import Environment


class Configuration(object):
    def __init__(
        self,
        environment: Environment,
        api_key: str,
        tenant_id: str,
        secret_path: str,
        roles: list,
        timeout: int = 30,
        jwt_expiration: datetime.datetime = datetime.datetime.utcnow() + datetime.timedelta(minutes=5),
        algorithm: str = 'RSA'
    ):
        self._environment = environment
        self._api_key = api_key
        self._tenant_id = tenant_id
        self._secret_path = secret_path
        self._roles = roles
        self._algorithm = algorithm
        self._timeout = timeout
        self._jwt_expiration = jwt_expiration
        self._jwt = self._generate_jwt_token()

    def _generate_jwt_token(self):
        # TODO: Getni secret z pathu (secret_path)
        # return jwt.encode(
        #     payload={
        #         'exp': self._expiration,
        #         'roles': self._roles
        #     },
        #     key=self._secret_path,
        #     headers={
        #         'alg' = self._algorithm,
        #         'typ': 'JWT'
        #         'kid': self._tenant_id
        #     }
        # )

        # TODO: Toto daj prec ked budu vygenerovane public/private RSA keys
        env_file = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), '.env')

        if os.path.exists(env_file):
            load_dotenv(dotenv_path=env_file, verbose=True)

        return os.getenv('DEFAULT_JWT_TOKEN')

    @property
    def environment(self) -> Environment:
        return self._environment

    @property
    def api_key(self) -> str:
        return self._api_key

    @property
    def tenant_id(self) -> str:
        return self._tenant_id

    @property
    def roles(self) -> list:
        return self._roles

    @property
    def secret_path(self) -> str:
        return self._secret_path

    @property
    def algorithm(self) -> str:
        return self._algorithm

    @property
    def timeout(self) -> int:
        return self._timeout

    def jwt_expiration(self) -> datetime.datetime:
        return self._jwt_expiration

    @property
    def jwt(self) -> str:
        return self._jwt

    def jwt_refresh(self):
        self._jwt = self._generate_jwt_token()
        return self._jwt
