# coding:utf-8

from datetime import date

from api.models.face import ScanSkinVideo
from rpc.cache import scan_skin_video_unlock_cache as unlock_cache

from rpc.decorators import bind_context
from api.tool.user_tool import get_user_from_context
from gm_types.gaia import AI_VIDEO_CHANNEL


def get_unlock_count(user_id, channel):

    if channel == AI_VIDEO_CHANNEL.TEST_SKIN:
        unlock_count_key = "{user_id}".format(user_id=user_id)
        day_unlock_key = "{day}:{user_id}".format(day=str(date.today()), user_id=user_id)
    else:
        unlock_count_key = "{user_id}:{channel}".format(user_id=user_id, channel=channel)
        day_unlock_key = "{day}:{user_id}:{channel}".format(day=str(date.today()), user_id=user_id, channel=channel)

    is_set = unlock_cache.set(day_unlock_key, 1, nx=True)
    if is_set:
        return int(unlock_cache.incr(unlock_count_key))

    return int(unlock_cache.get(unlock_count_key) or 0)


@bind_context('api/face_app/scan_skin_videos')
def have_scan_face_and_skin(ctx, channel=AI_VIDEO_CHANNEL.TEST_SKIN):

    unlock_count = 0
    user = get_user_from_context(ctx)
    if user:
        unlock_count = get_unlock_count(user.id, channel)

    result = {"videos": [], "unlock_count": unlock_count}
    for video in ScanSkinVideo.objects.filter(is_online=True, channel=channel).order_by("weight"):
        result["videos"].append(video.detail())

    return result

