from TDhelper.network.http.REST_HTTP import POST, GET
from datetime import datetime, timedelta, timezone
import json


class token_manage:
    __token = None
    __expire = None
    __token_service_uri = None
    __service_key = None
    __service_secret = None
    __time_cls = None

    @property
    def Token(self):
        if not self.__token:
            self.__get_token__()
        if self.__expire:
            if datetime.strptime(self.__expire,"%Y-%m-%d %H:%M:%S.%f") < self.__time_cls.now():
                self.__get_token__()
        return self.__token

    def __init__(self, token_uri:str, svr_key:str, secret:str, time_cls=None) -> None:
        self.__time_cls = datetime if not time_cls else time_cls
        self.__service_key = svr_key
        self.__service_secret = secret
        token_uri= token_uri.rstrip('/')
        self.__token_service_uri = "/".join([token_uri, "api/rpc_token"])
        self.__get_token__()

    def __get_token__(self):
        try:
            state, body = GET(self.__token_service_uri, {
                "svr_key": self.__service_key.upper(),
                "secret": self.__service_secret
            })
            if state:
                data = json.loads(body)
                self.__token = data.get("msg").get("token", None)
                self.__expire = data.get("msg").get("expire", None).replace("T"," ")
        except Exception as e:
            raise e
