# coding=utf-8
from __future__ import unicode_literals, absolute_import, print_function
from datetime import datetime

from api.models.variety_vote import VarietyActivity, UserInviteCode
from rpc.cache import variety_cache
from rpc.tool.error_code import CODES, gen


lock_user_key_tpl = "invite_code_{0}"


def get_current_activity_by_time(now_time=None):
    """根据时间获取当前活动id，如果没有当前活动则返回最近结束的活动。

    end: 是否是已经结束的活动
    activity: 活动
    """

    end = False
    now_time = now_time if now_time else datetime.now()
    activity = VarietyActivity.objects.filter(is_online=True, start_time__lte=now_time, end_time__gte=now_time).\
        order_by("start_time").first()

    if not activity:
        end = True
        activity = VarietyActivity.objects.filter(is_online=True, end_time__lt=now_time).order_by("-end_time").first()

    if not activity:
        end = True
        activity = VarietyActivity.objects.filter(is_online=True, start_time__gt=now_time).order_by("start_time").first()

    return activity, end


def lock_user_invite_code(user_id):
    """锁定用户邀请，防止刷票（代码操作间隙）"""

    key = lock_user_key_tpl.format(user_id)
    if variety_cache.get(key):
        gen(CODES.HAS_INVITED)

    variety_cache.set(key, 1, 1 * 60 * 60)


def unlock_user_invite_code(user_id):

    key = lock_user_key_tpl.format(user_id)
    variety_cache.delete(key)
