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

import shortuuid
from django.conf import settings
from django_logit import logit
from django_query import get_query_value
from django_response import response
from json_render import json_render

from guideline.models import ScreenAdminInfo
from utils.error.errno_utils import PermissionStatusCode, ScreenStatusCode
from utils.redis.connect import r
from utils.redis.rkeys import SCREEN_ADMIN_LOGIN


@logit
def screen_admin_oauthqr(request):
    brand_id = request.GET.get('brand_id', settings.KODO_DEFAULT_BRAND_ID)

    return json_render(request, 'page/screen_admin_oauth_qrcode.html', unjsondumpsdict={
        'qr': settings.KODO_SCREEN_AUTH_URL.format(brand_id)
    })


@logit
def screen_admin_oauth(request):
    brand_id = request.GET.get('brand_id', settings.KODO_DEFAULT_BRAND_ID)
    unionid = request.GET.get('unionid', '')
    openid = request.GET.get('openid', '')

    ScreenAdminInfo.objects.update_or_create(brand_id=brand_id, unionid=unionid, openid=openid, defaults={
        'nickname': request.GET.get('nickname', ''),
        'avatar': request.GET.get('avatar', '') or request.GET.get('headimgurl', ''),
        'user_status': ScreenAdminInfo.ACTIVATED,
    })

    return json_render(request, 'page/screen_admin_oauth_success.html', unjsondumpsdict={
    })


@logit
def screen_admin_loginqr(request):
    brand_id = get_query_value(request, 'brand_id', settings.KODO_DEFAULT_BRAND_ID)

    token = shortuuid.uuid()

    return response(200, data={
        'qr': settings.KODO_SCREEN_LOGIN_URL.format(brand_id, token),
        'token': token,
    })


@logit
def screen_admin_login(request):
    brand_id = request.GET.get('brand_id', settings.KODO_DEFAULT_BRAND_ID)
    unionid = request.GET.get('unionid', '')
    openid = request.GET.get('openid', '')
    token = request.GET.get('token', '')

    try:
        admin = ScreenAdminInfo.objects.get(unionid=unionid, user_status=ScreenAdminInfo.ACTIVATED)
    except ScreenAdminInfo.DoesNotExist:
        return json_render(request, 'page/screen_admin_login_fail.html', unjsondumpsdict={
        })

    r.setex(SCREEN_ADMIN_LOGIN % (brand_id, token), r.REDIS_EXPIRED_HALF_HOUR, unionid)

    return json_render(request, 'page/screen_admin_login_success.html', unjsondumpsdict={
    })


@logit
def screen_admin_loginrst(request):
    brand_id = get_query_value(request, 'brand_id', settings.KODO_DEFAULT_BRAND_ID)
    token = get_query_value(request, 'token', '')

    admin_login_key = SCREEN_ADMIN_LOGIN % (brand_id, token)

    if not r.exists(admin_login_key):
        return response(ScreenStatusCode.QRCODE_NOT_SCAN)

    unionid, _ = r.getdelete(admin_login_key)

    try:
        admin = ScreenAdminInfo.objects.get(unionid=unionid, user_status=ScreenAdminInfo.ACTIVATED)
    except ScreenAdminInfo.DoesNotExist:
        return response(PermissionStatusCode.PERMISSION_DENIED)

    return response(200, data={
        'info': admin.data,
    })
