import jwt
from Ansjer.config import UID_TOKEN_KEY


class UidTokenObject:

    def __init__(self, token=None):
        self.token = token
        self.UID = ''
        self.channel = ''
        self.flag = self.valid()

    def valid(self):
        token = self.token
        if self.token is None:
            return False
        try:
            res = jwt.decode(token, UID_TOKEN_KEY, algorithms='HS256')
            print(res)
            UID = res.get('uid', None)
            channel = res.get('channel', None)
            if UID is None:
                return False
            self.UID = UID
            self.channel = channel
        except jwt.ExpiredSignatureError as e:
            print('过期')
            print(repr(e))
        except Exception as e:
            print(repr(e))

    def generate(self, data=None):
        if data is None:
            data = {}
        token = jwt.encode(data, UID_TOKEN_KEY, algorithm='HS256')
        self.token = token
        return token
