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

from __future__ import division

from django_logit import logit
from django_response import response
from TimeConvert import TimeConvert as tc

from account.models import UserInfo
from group.models import GroupInfo, GroupUserInfo
from utils.error.errno_utils import GroupStatusCode, GroupUserStatusCode, UserStatusCode
from utils.group_photo_utils import get_current_photos
from utils.redis.connect import r
from utils.redis.rgroup import get_group_info, get_group_users_info, set_group_users_info
from utils.redis.rkeys import (GROUP_LAST_PHOTO_PK, GROUP_USERS_DELETED_SET, GROUP_USERS_PASSED_SET,
                               GROUP_USERS_QUIT_SET, GROUP_USERS_REFUSED_SET)


@logit
def group_user_join_api(request):
    """ 群成员加群 """
    group_id = request.POST.get('group_id', '')
    user_id = request.POST.get('user_id', '')
    nickname = request.POST.get('nickname', '')

    # 用户校验
    try:
        user = UserInfo.objects.get(user_id=user_id, status=True)
    except UserInfo.DoesNotExist:
        return response(UserStatusCode.USER_NOT_FOUND)

    # 群组校验
    try:
        group = GroupInfo.objects.get(group_id=group_id, status=True)
    except GroupInfo.DoesNotExist:
        return response(GroupStatusCode.GROUP_NOT_FOUND)

    # 群组锁定校验
    if group.group_lock:
        return response(GroupStatusCode.GROUP_HAS_LOCKED)

    # 群组用户记录创建，若记录不存在，则创建，若记录已存在，则更新
    group_user, created = GroupUserInfo.objects.get_or_create(
        group_id=group_id,
        user_id=user_id,
    )
    if group_user.user_status != GroupUserInfo.PASSED:
        group_user.current_id = -1 if group.group_from == GroupInfo.SESSION_GROUP else int(r.get(GROUP_LAST_PHOTO_PK % group_id) or -1)
        group_user.nickname = nickname or user.final_nickname
        group_user.avatar = user.avatar
        # group_user.admin = False  # Admin Field Default False, Should Not Assign
        group_user.user_status = GroupUserInfo.PASSED
        group_user.passed_at = tc.utc_datetime()
        group_user.save()

    # Redis 群组用户数据缓存
    set_group_users_info(group)

    # Redis 群组通过集合缓存
    r.srem(GROUP_USERS_REFUSED_SET % group_id, user_id)
    r.srem(GROUP_USERS_DELETED_SET % group_id, user_id)
    r.srem(GROUP_USERS_QUIT_SET % group_id, user_id)
    r.sadd(GROUP_USERS_PASSED_SET % group_id, user_id)

    curinfo = get_current_photos(group_id, user_id, group_user.current_id, request=request)

    return response(200, 'Group User Join Success', u'群成员加群成功', {
        'current_id': curinfo.get('current_id', ''),
        'photos': curinfo.get('photos', ''),
        'group_id': group_id,
        'group': get_group_info(group_id),
        'user_id': user_id,
        'users': get_group_users_info(group_id, user_id),
    })


@logit
def group_user_remove_api(request):
    """ 群成员移除，管理员主动，群成员被动 """
    group_id = request.POST.get('group_id', '')
    admin_id = request.POST.get('admin_id', '')
    user_id = request.POST.get('user_id', '')

    # 群组校验
    try:
        group = GroupInfo.objects.get(group_id=group_id, status=True)
    except GroupInfo.DoesNotExist:
        return response(GroupStatusCode.GROUP_NOT_FOUND)

    # 权限校验
    if group.admin_id != admin_id:
        return response(GroupStatusCode.NOT_GROUP_ADMIN)

    # 管理员也不允许将自己移除
    if group.admin_id == user_id:
        return response(GroupStatusCode.ADMIN_CANNOT_HANDLE_SELF)

    # 群组用户校验
    try:
        group_user = GroupUserInfo.objects.get(group_id=group_id, user_id=user_id, status=True)
    except GroupUserInfo.DoesNotExist:
        return response(GroupUserStatusCode.GROUP_USER_NOT_FOUND)

    # 群组用户移除
    group_user.user_status = GroupUserInfo.DELETED
    group_user.deleted_at = tc.utc_datetime()
    group_user.save()

    # Redis 群组数据缓存更新
    group_users = set_group_users_info(group)

    # Redis 群组删除集合缓存
    r.srem(GROUP_USERS_PASSED_SET % group_id, user_id)
    r.sadd(GROUP_USERS_DELETED_SET % group_id, user_id)

    return response(200, 'Group User Remove Success', u'群成员移除成功', {
        'group_id': group_id,
        'users': group_users,
    })


@logit
def group_user_quit_api(request):
    """ 群成员退出，群成员主动 """
    group_id = request.POST.get('group_id', '')
    user_id = request.POST.get('user_id', '')

    # 群组校验
    try:
        group = GroupInfo.objects.get(group_id=group_id, status=True)
    except GroupInfo.DoesNotExist:
        return response(GroupStatusCode.GROUP_NOT_FOUND)

    # 权限校验
    if group.admin_id == user_id:  # 管理员也不允许自己退出
        return response(GroupStatusCode.NOT_GROUP_ADMIN)

    # 群组用户校验
    try:
        group_user = GroupUserInfo.objects.get(group_id=group_id, user_id=user_id, status=True)
    except GroupUserInfo.DoesNotExist:
        return response(GroupUserStatusCode.GROUP_USER_NOT_FOUND)

    # 群组用户移除
    group_user.user_status = GroupUserInfo.QUIT
    group_user.quit_at = tc.utc_datetime()
    group_user.save()

    # Redis 群组数据缓存更新
    group_users = set_group_users_info(group)

    # Redis 群组删除集合缓存
    r.srem(GROUP_USERS_PASSED_SET % group_id, user_id)
    r.sadd(GROUP_USERS_QUIT_SET % group_id, user_id)

    return response(200, 'Group User Quit Success', u'群成员退出成功', {
        'group_id': group_id,
        'users': group_users,
    })
