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

import time

import shortuuid
from django.conf import settings
from django.shortcuts import redirect
from furl import furl
from json_response import auto_response
from pywe_oauth import get_access_info, get_oauth_code_url, get_userinfo
from wechatpy import WeChatClient


JSAPI = settings.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', '')

    if request.weixin:
        redirect_uri = settings.WECHAT_USERINFO_REDIRECT_URI if scope == 'snsapi_userinfo' else settings.WECHAT_BASE_REDIRECT_URI
        return redirect(get_oauth_code_url(JSAPI['appID'], redirect_uri, scope, 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 = get_access_info(JSAPI['appID'], JSAPI['appsecret'], code)

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


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

    access_info = get_access_info(JSAPI['appID'], JSAPI['appsecret'], code)
    userinfo = get_userinfo(access_info.get('access_token', ''), access_info.get('openid', ''))

    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,
    }
