# coding=utf-8
from __future__ import unicode_literals

import time
from hashlib import md5

import requests
from django.conf import settings
from Crypto.Cipher import AES

from api.models import LOGIN_AUTH_TYPE


__author__ = 'leaf'


def get_auth_info(auth_type, access_token):
    auth_user_id = ''
    message = ''
    error = 0

    if auth_type == 'SinaWeibo':
        dict, status_code = get_sina_weibo_token_info(access_token)
        if status_code == 200:
            auth_user_id = dict["uid"]
        else:
            message = dict["error"]
            error = dict["error_code"]
        result = {"auth_user_id": auth_user_id,
                  "login_auth_type": LOGIN_AUTH_TYPE.SinaWeibo,
                  "error": error,
                  "message": message}

    elif auth_type == 'life_360':
        dict = get_life_360_token_info(access_token)
        if dict["errno"] == 0:
            mobile = dict["data"]["mobile"]
            auth_user_id = decrypt_mode_ecb(mobile, settings.LIFE_360_SECRET_KEY)

        result = {"auth_user_id": auth_user_id[:11],
                  "login_auth_type": LOGIN_AUTH_TYPE.life_360,
                  "error": dict["errno"],
                  "message": dict["errmsg"]}

    return result

def get_sina_weibo_token_info(access_token):
    """
    用于获取新浪微信信息
    :param access_token:
    :return:
    """
    data = {"access_token": access_token}
    response = requests.post(settings.SINA_WEIBO_GET_UID_URL, data)
    return response.json(), response.status_code

def get_life_360_token_info(access_token):
    """
    用户获取360生活助手信息
    :param access_token:
    :return:
    """
    ts = time.time()
    params = {
        "token": access_token,
        "cp": settings.LIFE_360_QID,
        "ts": ts
    }
    sign_str, get_params_str = _params_sort(params)
    private_key = settings.LIFE_360_SECRET_KEY
    sign = _generate_md5_sign(sign_str, private_key)
    get_params_str = '{}sign={}'.format(get_params_str, sign)
    response = requests.get(u'{}?{}'.format(settings.LIFE_360_GET_MOBILE_URL, get_params_str))
    return response.json()

def _params_sort(params):
    """
    将请求中所有参数的参数名进行排序, 排序为字典序
    :param params: 待过滤字典
    :return
        sign_str: 待签名字符串
        get_params_str: get参数拼接
    """
    ks = params.keys()
    ks.sort()
    sign_str = ''
    get_params_str = ''
    for k in ks:
        v = params[k]
        sign_str += '{}={}'.format(k, v)
        get_params_str += '{}={}&'.format(k, v)
    return sign_str, get_params_str

def _generate_md5_sign(sign_str, private_key):
    """
    生成MD5签名结果
    :param sign_str: 待签名字符串
    :param private_key: 私钥
    :return:
    """
    return md5(sign_str + private_key).hexdigest()

def decrypt_mode_ecb(encrypted, key):
    """
    AES解密字符串
    :param encrypted: string 待解密的串
    :param key: string 密钥
    :return: string 解密后的结果
    """
    encrypted = encrypted.decode('base64')
    obj = AES.new(key, AES.MODE_ECB)
    return obj.decrypt(encrypted)
