import jwt
import time
from Ansjer.config import OAUTH_ACCESS_TOKEN_SECRET, OAUTH_REFRESH_TOKEN_SECRET, OAUTH_ACCESS_TOKEN_TIME, \
    OAUTH_REFRESH_TOKEN_TIME


class TokenObject:

    def __init__(self, token=None, returntpye='currency'):
        if token == 'local':
            token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTg0MzUxODk2MjgyMTM4MDAxMzgwMDAiLCJsYW5nIjoiZW4iLCJ1c2VyIjoiMTM2ODAzMTc1OTYiLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJleHAiOjE1ODcyNzcwNjB9.c0LV_XyxwbzUlYqMJqx7vw9f19Jv-0kGnUHuu_go-mo'
        if token == 'test':
            token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiMTM4MDAxMzgwMDEiLCJleHAiOjE1Njk5OTg4OTYsInVzZXJJRCI6IjE1MTU2NDI2MjMzNzkzOTUxMzgwMDEzODAwMSIsImxhbmciOiJlbiIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCJ9.VAQtT9AbCCfXcrNj9DL5cvVasMDoI7AP8ptgU1GoMu8'
        self.token = token
        self.lang = None
        self.userID = None
        self.user = ''
        self.code = 0
        self.valid()
        self.returntpye = returntpye

    def valid(self):
        if self.token is None:
            self.code = 309
            return
        try:
            self.token = self.token.replace("Bearer ", "")

            res = jwt.decode(self.token, OAUTH_ACCESS_TOKEN_SECRET, algorithms='HS256')
            self.userID = res.get('userID', None)
            self.lang = res.get('lang', None)
            self.user = res.get('user', '')
            # 刷新登录时间
            # if self.userID:
            #     print(self.user)
            #     redisObj = RedisObject(db=3)
            #     redisObj.set_data(key=self.userID, val=self.user, expire=300)

        except jwt.ExpiredSignatureError as e:
            self.code = 309
            return
        except Exception as e:
            self.code = 309
            return
        else:
            if not self.userID:
                self.code = 309
                return
            else:
                if self.userID:
                    self.code = 0
                    return res
                else:
                    self.code = 309
                    return

    def generate(self, data=None):
        if data is None:
            data = {}
        try:
            access_expire = int(OAUTH_ACCESS_TOKEN_TIME.total_seconds())
            refresh_expire = int(OAUTH_REFRESH_TOKEN_TIME.total_seconds())
            now_stamp = int(time.time())
            access_data = data
            refresh_data = data
            access_data['exp'] = access_expire + now_stamp
            refresh_data['exp'] = refresh_expire + now_stamp
            access_token = jwt.encode(access_data,
                                      OAUTH_ACCESS_TOKEN_SECRET,
                                      algorithm='HS256')
            refresh_token = jwt.encode(
                refresh_data,
                OAUTH_REFRESH_TOKEN_SECRET,
                algorithm='HS256')

            res = {
                'access_token': access_token,
                'access_expire': access_expire,
                'refresh_expire': refresh_expire,
                'refresh_token': refresh_token,
            }

            if self.returntpye=='pc':
                res = {
                    'token': access_token,
                    'access_expire': access_expire,
                    'refresh_expire': refresh_expire,
                    'refresh_token': refresh_token,
                }

        except Exception as e:
            self.code = 309
            print(repr(e))
        else:
            self.code = 0
            return res

    def encryption(self, data=None):
        if data is None:
            data = {}
        try:
            access_expire = int(OAUTH_ACCESS_TOKEN_TIME.total_seconds())
            refresh_expire = int(OAUTH_REFRESH_TOKEN_TIME.total_seconds())
            now_stamp = int(time.time())
            access_data = data
            refresh_data = data
            access_data['exp'] = access_expire + now_stamp
            refresh_data['exp'] = refresh_expire + now_stamp
            access_token = jwt.encode(access_data,
                                      OAUTH_ACCESS_TOKEN_SECRET,
                                      algorithm='HS256')
            return access_token
        except Exception as e:
            self.code = 309
            print(repr(e))

    def refresh(self):
        if not self.token:
            self.code = 309
            return
        try:
            res = jwt.decode(self.token, OAUTH_REFRESH_TOKEN_SECRET, algorithms='HS256')
        except jwt.ExpiredSignatureError as e:
            print('过期')
            print(repr(e))
            self.code = 309
        except Exception as e:
            self.code = 309
            print(repr(e))
        else:
            self.code = 0
            userID = res.get('userID', '')
            user = res.get('user', '')
            lang = self.lang
            self.userID = userID
            self.user = user
            refreshRes = self.generate(data={'userID': userID, 'lang': lang, 'user': user})
            return refreshRes
