# -*- coding: utf-8 -*-

import time
import urllib

import requests
import shortuuid
from CodeConvert import CodeConvert as cc
from django.conf import settings
from django.shortcuts import redirect
from furl import furl
from json_response import auto_response
from pysnippets import dictsnippets as dsnippets
from wechatpy import WeChatClient


r = settings.REDIS_CACHE
WECHAT = settings.WECHAT
JSAPI = WECHAT.get('JSAPI', {})


def get_openid(request):
    scope = request.GET.get('scope', 'snsapi_userinfo')
    redirect_url = request.GET.get('redirect_url', '')
    default_url = request.GET.get('default_url', '')

    if request.weixin:
        authorize_url = settings.WECHAT_GET_CODE_USERINFO if scope == 'snsapi_userinfo' else settings.WECHAT_GET_CODE_BASE
        get_code_url = authorize_url % (JSAPI['appID'], urllib.quote_plus(settings.WECHAT_REDIRECT_URI), urllib.quote_plus(redirect_url))
        return redirect(get_code_url)

    return redirect(default_url if default_url else redirect_url)


def to_redirect(request):
    code = request.GET.get('code', '')
    state = request.GET.get('state', '')

    access_info = requests.get(settings.WECHAT_GET_OAUTH2_ACCESS_TOKEN % (JSAPI['appID'], JSAPI['appsecret'], code), verify=False).json()
    unionid, openid, access_token = access_info.get('unionid', ''), access_info.get('openid', ''), access_info.get('access_token', '')

    res = requests.get(settings.WECHAT_GET_USERINFO % (access_token, openid), verify=False)
    res.encoding = 'utf-8'
    userinfo = res.json()

    return redirect(furl(state).add(cc.Convert2Utf8(dsnippets.filter(userinfo, ['unionid', 'openid', 'nickname', 'headimgurl']))).url)


@auto_response
def wx_jsapi_signature_api(request):
    url = request.GET.get('url', '')

    nonceStr, timestamp = shortuuid.uuid(), int(time.time())

    client = WeChatClient(JSAPI['appID'], JSAPI['appsecret'])
    ticket = client.jsapi.get_jsapi_ticket()
    signature = client.jsapi.get_jsapi_signature(nonceStr, ticket, timestamp, url)

    return {
        'appId': JSAPI['appID'],
        'nonceStr': nonceStr,
        'timestamp': timestamp,
        'signature': signature,
    }
