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

from group.models import GroupInfo, GroupPhotoInfo, GroupUserInfo, PhotoCommentInfo, PhotoThumbUpInfo
from utils.redis.connect import r
from utils.redis.rgroup import set_group_photo_data, set_group_users_info
from utils.redis.rkeys import (GROUP_LAST_PHOTO_PK, GROUP_PHOTO_WATCHER_SET, GROUP_USERS_APPLYING_SET,
                               GROUP_USERS_DELETED_SET, GROUP_USERS_PASSED_SET, GROUP_USERS_REFUSED_SET)


def retrieve_group_data():
    """ 群组数据 """
    groups = GroupInfo.objects.filter(status=True)
    for group in groups:
        # 群组照片
        set_group_photo_data(group.group_id)
        # 群组用户
        set_group_users_info(group)


def retrieve_last_pk():
    """ 群组最后一张照片PK """
    groups = GroupInfo.objects.filter(status=True)
    for group in groups:
        group_photo = GroupPhotoInfo.objects.filter(group_id=group.group_id, status=True).last()
        r.set(GROUP_LAST_PHOTO_PK % group.group_id, group_photo and group_photo.pk or -1)


def retrieve_group_user_status():
    """ 群组用户状态 """
    group_users = GroupUserInfo.objects.filter(status=True)
    for group_user in group_users:
        group_id, user_id = group_user.group_id, group_user.user_id
        if group_user.user_status == GroupUserInfo.PASSED:
            r.sadd(GROUP_USERS_PASSED_SET % group_id, user_id)
        elif group_user.user_status == GroupUserInfo.DELETED:
            r.sadd(GROUP_USERS_DELETED_SET % group_id, user_id)
        elif group_user.user_status == GroupUserInfo.APPLYING:
            r.sadd(GROUP_USERS_APPLYING_SET % group_id, user_id)
        elif group_user.user_status == GroupUserInfo.REFUSED:
            r.sadd(GROUP_USERS_REFUSED_SET % group_id, user_id)


def retrieve_group_photo_watchers():
    group_photos = GroupPhotoInfo.objects.filter(status=True)
    for group_photo in group_photos:
        photo_comments = PhotoCommentInfo.objects.filter(photo_id=group_photo.photo_id, status=True)
        for photo_comment in photo_comments:
            r.sadd(GROUP_PHOTO_WATCHER_SET % group_photo.pk, photo_comment.user_id)
        photo_thumbups = PhotoThumbUpInfo.objects.filter(photo_id=group_photo.photo_id, status=True)
        for photo_thumbup in photo_thumbups:
            r.sadd(GROUP_PHOTO_WATCHER_SET % group_photo.pk, photo_thumbup.user_id)


def retrieve_redis_data():
    retrieve_group_data()
    retrieve_last_pk()
    retrieve_group_user_status()
    retrieve_group_photo_watchers()
