import secrets
import hashlib
from typing import Dict,Any
import jwt
from datetime import datetime
def generate_client_id():
    """Generate a random client ID."""
    return secrets.token_urlsafe(16)

def generate_client_secret():
    """Generate a random client secret."""
    return hashlib.sha256(secrets.token_bytes(16)).hexdigest()

class Sign(object):
    def __init__(self) -> None:
        super().__init__()
        self._param = ""

    @property
    def param(self):
        return self._param

    @param.setter
    def param(self, value):
        self._param = value

    def _md5(self, _str):
        # 创建md5对象
        hl = hashlib.md5()
        # Tips
        # 此处必须声明encode
        # 若写法为hl.update(str)  报错为： Unicode-objects must be encoded before hashing
        hl.update(_str.encode(encoding='utf-8'))
        return hl.hexdigest()

    def sign(self):
        '''签名计算'''
        keys = sorted(self._param.keys())
        key_str = "".join(keys)
        values_str = ""
        for key in keys:
            values_str += str(self._param[key])
        s = "{}{}".format(
            key_str,
            values_str.replace('\'', '').replace(' ', '').replace('\"', ''))
        # 加密
        signature_str1 = self._md5(s)
        # 加盐加密
        signature_str = self._md5("NCSS-SASH-{}".format(signature_str1))
        return signature_str



class OAuth2SessionManager:
    def __init__(self, client_id, client_secret):
        self.client_id = client_id
        self.client_secret = client_secret
        self.access_token = None
        self.issued_at = None
        self.expires_at = None
        self.algorithm = "HS256"
    
    def refresh_token(self,jwt_token_info:Dict[str,Any]):
        jwt_token_info.update({
            "client_id":self.client_id,
            "client_secret":self.client_secret
        })
        self.access_token = jwt.encode(jwt_token_info, 'secret', algorithm=self.algorithm)
        self.expires_at = datetime.fromtimestamp(jwt_token_info['expires_at'])

    def check_token(self,token):
        jwt_token = jwt.decode(token, 'secret', algorithms=self.algorithm)
        client_id = jwt_token.get("client_id")
        client_secret = jwt_token.get("client_secret")
        print(f"client_id:{client_id};client_secret:{client_secret}")
        if (client_id!=self.client_id) or (client_secret!=self.client_secret):
            return False
        return True