# -*- coding: utf8 -*-
from __future__ import unicode_literals, absolute_import, print_function

import datetime

from django.conf import settings
from gm_types.push import PERSONAL_PUSH_TYPE

from rpc.cache import user_cache, push_cache
from rpc.context import get_rpc_remote_invoker
from talos.backbone.outer_sys_models import eta_2_push_time
from talos.backbone.rpc import logging_exception


def limit_push(user_id, sign):
    """
    推送限制,每种类型每天只能推送一次
    :param user_id: 用户id,用于生成唯一redis_name
    :param sign:  推送所属类型，e.g: favor --> 收藏
    :return: True ok，False off;
    """
    sign = sign.strip()
    today = datetime.datetime.today()  # 当前时间
    # 推送时间限制
    hour = today.hour
    if hour < 9 or hour >= 22:
        return False

    name = "{0}_personal_push_{1}".format(user_id, today.strftime("%Y-%m-%d"))

    # 推送类型及条数，类型：fans 粉丝、vote 点赞、favor 收藏、reply 回复、total 总值。
    if sign not in PERSONAL_PUSH_TYPE:
        return False

    if user_cache.exists(name):
        sign_val, total = user_cache.hmget(name, sign, "total")
        if int(total) >= settings.PUSH_TOTAL_LIMIT:
            return False
        if sign_val and int(sign_val) >= settings.PUSH_SUB_LIMIT:
            return False

        user_cache.hincrby(name, sign, amount=1)
        user_cache.hincrby(name, "total", amount=1)
    else:
        dic = {"total": 1, sign: 1}
        # 用于设置失效时间，仅当天有效
        user_cache.hmset(name, dic)
        user_cache.expire(name, (today.replace(hour=22, minute=1, second=0) - today).seconds)

    return True


def special_push_limit(user_id, push_type, extra=None):
    # 感觉所有推送的限制可以放到推送服务里面，或者考虑加一层
    # emmm 在talos外面import了这个。。。
    now = datetime.datetime.now()
    hour = now.hour
    if hour < 9 or hour >= 22:
        return False

    total_key = "total:{}:{}".format(now.strftime("%Y-%m-%d"), user_id)
    total = push_cache.get(total_key)
    if total and int(total) >= settings.SPECIAL_PUSH_LIMIT:
        return False

    sub_key = [push_type, user_id, ]
    if extra is not None:
        if isinstance(extra, (list, tuple)):
            sub_key += list(extra)
        else:
            sub_key.append(extra)
    sub_key = ":".join(map(str, sub_key))
    pushed = push_cache.get(sub_key)
    if pushed:
        return False

    if total:
        push_cache.incr(total_key)
    else:
        push_cache.setex(total_key, 86400, 1)
    push_cache.setex(sub_key, settings.SPECTAL_SECONDS_LIMIT, True)
    return True
