import json
import requests
from datetime import datetime, timezone


class MagmaAuth:
    url_login = 'https://magma.esdm.go.id/api/login'
    url_validate_token = 'https://magma.esdm.go.id/api/status'

    def __init__(self, token: str = None) -> None:
        self.token = token
        self.expired = None

        if token is not None and self.token_is_valid(token):
            raise ValueError('Invalid token')

    @property
    def token(self) -> str | None:
        return self._token

    @token.setter
    def token(self, token: str) -> None:
        if token is not None and self.token_is_valid(token):
            self._token = token
        else:
            self._token = None

    def token_is_valid(self, token) -> bool:
        headers = {'Authorization': 'Bearer ' + token}

        try:
            response = requests.request("GET", self.url_validate_token, headers=headers).json()
            self.expired = datetime.fromtimestamp(response['exp'], timezone.utc)
        except Exception as e:
            raise f'Error validating token: {e}'

        if 'code' in response:
            if response['code'] == 419:
                return False

        return True

    def login(self, username: str, password: str) -> str:
        payload = json.dumps({
            "username": username,
            "password": password
        })

        headers = {'Content-Type': 'application/json'}

        try:
            response = requests.request("POST", self.url_login,
                                        headers=headers, data=payload).json()
        except Exception as e:
            raise f'Error login with username and password: {e}'

        if not response['success']:
            raise ValueError(f'Wrong username or password.')

        self.token = response['token']

        return response['token']
