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

import time
import urllib

import requests
import shortuuid
from django.conf import settings
from django.shortcuts import redirect
from furl import furl
from json_response import auto_response
from wechatpy import WeChatClient


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


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

    redirect_uri = settings.WECHAT_USERINFO_REDIRECT_URI if scope == 'snsapi_userinfo' else settings.WECHAT_BASE_REDIRECT_URI

    if request.weixin:
        return redirect(settings.WECHAT_OAUTH2_AUTHORIZE.format(
            appid=JSAPI['appID'],
            redirect_uri=urllib.quote_plus(redirect_uri),
            scope=scope,
            state=urllib.quote_plus(redirect_url)
        ))

    return redirect(default_url or redirect_url)


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

    access_info = requests.get(settings.WECHAT_OAUTH2_ACCESS_TOKEN.format(
        appid=JSAPI['appID'],
        secret=JSAPI['appsecret'],
        code=code
    ), verify=False).json()

    return redirect(furl(state).add(access_info).url)


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

    access_info = requests.get(settings.WECHAT_OAUTH2_ACCESS_TOKEN.format(
        appid=JSAPI['appID'],
        secret=JSAPI['appsecret'],
        code=code
    ), verify=False).json()
    openid, access_token = access_info.get('openid', ''), access_info.get('access_token', '')

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

    return redirect(furl(state).add(userinfo).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,
    }
