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

from __future__ import division

from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import transaction
from django.shortcuts import redirect
from furl import furl
from logit import logit

from account.models import UserInfo
from utils.redis.connect import r


@logit
@transaction.atomic
def oauth_redirect(request):
    unique_identifier = request.GET.get(settings.WECHAT_UNIQUE_IDENTIFICATION, '')

    user, created = UserInfo.objects.select_for_update().get_or_create(**{settings.WECHAT_UNIQUE_IDENTIFICATION: unique_identifier})
    user.unionid = request.GET.get('unionid', '')
    user.openid = request.GET.get('openid', '')
    user.nickname = request.GET.get('nickname', '')
    user.avatar = request.GET.get('headimgurl', '')
    user.save()

    token_check_key = user.user_id

    query_params = {
        settings.TOKEN_CHECK_KEY: token_check_key,
        'vtoken': r.token(token_check_key, ex=False, buf=False),
    }

    return redirect(furl(reverse('page:course_code')).add(request.GET).add(query_params).url)
