# -*- 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, render
from furl import furl

from account.models import UserInfo
from codes.models import CourseCodeInfo
from course.decorators import check_token
from utils.error.errno_utils import CourseCodeStatusCode, ProfileStatusCode
from utils.error.response_utils import response


@check_token
@transaction.atomic
def course_code(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()

    try:
        course_code = CourseCodeInfo.objects.get(user_id=user.user_id, exchanged=True, status=True)
    except CourseCodeInfo.DoesNotExist:
        course_code = None

    if course_code:
        return redirect(furl(reverse('page:course_list')).add(request.GET).add({'user_id': user.user_id}).url)

    return render(request, 'page/course_code.html', {
        'domain': settings.DOMAIN,
        'user_info': user.data,
        'params': 'user_id={}&vtoken={}'.format(user.user_id, request.GET.get('vtoken', '')),
    })


@transaction.atomic
def code_exchange(request):
    user_id = request.POST.get('user_id', '')
    code = request.POST.get('code', '')

    try:
        user = UserInfo.objects.select_for_update().get(user_id=user_id)
    except UserInfo.DoesNotExist:
        return response(ProfileStatusCode.PROFILE_NOT_FOUND)

    try:
        course_code = CourseCodeInfo.objects.select_for_update().get(code=code, status=True)
    except CourseCodeInfo.DoesNotExist:
        return response(CourseCodeStatusCode.COURSE_CODE_NOT_FOUND)

    if course_code.exchanged:
        return response(CourseCodeStatusCode.COURSE_CODE_HAS_EXCHANGED)

    course_code.user_id = user.user_id
    course_code.exchanged = True
    course_code.save()

    return response(200, 'Course Code Exchanged Success', u'课程兑换码兑换成功')
