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

from django.contrib.auth.models import Group, User
from django.db import transaction
from django_curtail_uuid import CurtailUUID
from django_logit import logit
from django_response import response
from ipaddr import client_ip
from rest_framework import viewsets
from TimeConvert import TimeConvert as tc

from account.models import LensmanInfo, UserInfo
from account.serializers import GroupSerializer, LensmanInfoSerializer, UserInfoSerializer, UserSerializer
from operation.models import GuestEntranceControlInfo
from utils.error.errno_utils import UserStatusCode
from utils.redis.rguest import get_guest_entrance_control
from utils.redis.rprofile import set_profile_info
from utils.version_utils import is_version_match


@logit
@transaction.atomic
def user_wx_authorize_api(request):
    # Get or Create User
    user, created = UserInfo.objects.select_for_update().get_or_create(unionid=request.POST.get('unionid', ''))

    # Set User_id
    if created:
        user.user_id = CurtailUUID.uuid(UserInfo, 'user_id')

    # Set User Key's Value
    user.user_from = UserInfo.USER_USER
    user.openid = request.POST.get('wx_uid', '')
    user.sex = request.POST.get('sex', 0)
    user.nickname = request.POST.get('nickname', '') or request.POST.get('screen_name', '')
    user.avatar = request.POST.get('headimgurl', '') or request.POST.get('profile_image_url', '')
    user.country = request.POST.get('country', '')
    user.province = request.POST.get('province', '')
    user.city = request.POST.get('city', '')
    user.user_status = UserInfo.ACTIVATED
    user.signup_ip = client_ip(request)
    user.signup_at = tc.utc_datetime()
    user.save()

    set_profile_info(user)

    return response(200, 'User Login Success', u'用户端登录成功', user.data)


@logit
@transaction.atomic
def user_guest_login_api(request):
    """ 游客登录 """
    gen = get_guest_entrance_control()

    # 是否配置游客入口控制信息
    if not gen:
        return response(UserStatusCode.GUEST_NOT_ALLOWED)

    # 平台校验
    platform = gen.get('platform', '')
    if request.Android:
        if platform not in [GuestEntranceControlInfo.ADR, GuestEntranceControlInfo.BOTH]:
            return response(UserStatusCode.GUEST_NOT_ALLOWED)
    else:
        if platform not in [GuestEntranceControlInfo.IOS, GuestEntranceControlInfo.BOTH]:
            return response(UserStatusCode.GUEST_NOT_ALLOWED)

    # 版本校验
    if not is_version_match(request, gen):
        return response(UserStatusCode.GUEST_NOT_ALLOWED)

    # 通用唯一识别码 (Universally Unique Identifier)
    uuid = request.POST.get('uuid', '')
    # 游客字段
    fields = {
        'user_id': CurtailUUID.uuid(UserInfo, 'user_id'),
        'user_from': UserInfo.GUEST_USER,
        'uuid': uuid,
        'nickname': u'游客',
        'user_status': UserInfo.ACTIVATED,
    }
    # 若 uuid 存在，则 get_or_create，否则 create
    if uuid:
        user, created = UserInfo.objects.select_for_update().get_or_create(user_from=UserInfo.GUEST_USER, uuid=uuid, defaults=fields)
        if created:
            user.nickname = u'游客{}'.format(user.pk)
            user.save()
    else:
        user = UserInfo.objects.select_for_update().create(**fields)
        user.nickname = u'游客{}'.format(user.pk)
        user.save()

    return response(200, 'Guest Login Success', u'游客登录成功', user.data)


class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-pk')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer


class LensmanInfoViewSet(viewsets.ModelViewSet):
    queryset = LensmanInfo.objects.all().order_by('-pk')
    serializer_class = LensmanInfoSerializer


class UserInfoViewSet(viewsets.ModelViewSet):
    queryset = UserInfo.objects.all().order_by('-pk')
    serializer_class = UserInfoSerializer
