# 制作一个加密工具和一个解密工具。
# 到一个密钥包----itsdangerous
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData

from users.models import User


def generate_openid_signature(openid):
    # 对openid进行加密, 并返回加密后的openid

    # 创建加密对象
    serializer = Serializer(settings.SECRET_KEY, 600)  # settings.SECRET_KEY 设置里面默认的加密格式导入进去

    # 包装加密数据
    data = {"openid": openid}

    # 调用它的dumps方法,需要将加密的数据包装成字典格式, 加密后返回bytes
    # dumps方法在json包里面是把字典转成json格式字符串
    openid_signg_bytes = serializer.dumps(data)

    # 返回加密openid
    return openid_signg_bytes.decode()


def check_openid_signature(sign_openid):
    # 对openid进行解密, 并返回解密后的openid
    print(sign_openid)
    # 创建解密对象
    serializer = Serializer(settings.SECRET_KEY, 600)

    # 解密之后也是一个字典 因为加密是字典
    # loads方法用来解密
    try:
        data = serializer.loads(sign_openid)
    except BadData:  # 不理解
        print(BadData)
        return None
    else:
        # 返回解密openid
        return data.get('openid')

def generate_verify_email_url(user):
    """拼接用户邮箱激活url"""
    # 创建加密对象
    serializer = Serializer(settings.SECRET_KEY, 60 * 60 * 24)
    # 包装要加密的字典数据
    data = {'user_id': user.id, 'email': user.email}
    # 对字典进行加密
    token = serializer.dumps(data).decode()
    # 拼接用户激活邮箱url
    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token
    return verify_url


def check_verify_email_token(token):
    """对token进行解密并返回user或None"""
    # 创建加密对象
    serializer = Serializer(settings.SECRET_KEY, 60 * 60 * 24)
    try:
        data = serializer.loads(token)  # 解密
        user_id = data.get('user_id')  # 解密没有问题后取出里面数据
        email = data.get('email')
        try:
            user = User.objects.get(id=user_id, email=email)  # 查询唯一用户
            return user  # 查询到直接返回
        except User.DoesNotExist:
            return None

    except BadData:
        return None


import requests
import json

# requests完成 访问微博 SDK
class OAuthWB:
    def __init__(self, client_id, client_key, redirect_uri):
        self.client_id = client_id
        self.client_key = client_key
        self.redirect_uri = redirect_uri

    def get_access_token(self, code):  # 获取用户token和uid
        url = "https://api.weibo.com/oauth2/access_token"

        querystring = {
            "client_id": self.client_id,
            "client_secret": self.client_key,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": self.redirect_uri
        }

        response = requests.request("POST", url, params=querystring)

        return json.loads(response.text)

    def get_user_info(self, access_token_data):
        url = "https://api.weibo.com/2/users/show.json"

        querystring = {
            "uid": access_token_data['uid'],
            "access_token": access_token_data['access_token']
        }

        response = requests.request("GET", url, params=querystring)

        return json.loads(response.text)
