#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from gm_rpcd.all import bind, RPCDFaultException
from gm_types.push import PUSH_CONTENT_TYPE

from communal.tools import PushService
from communal.tools.push.push_builder import CtrPushContentFormat
from communal.models.hot_content import HotContent
from utils.rpc import logging_exception


@bind("mimas/communal/push_service")
def mimas_call_push_logic(user_ids, action_type, is_timely_push, **kwargs):
    """
    推送逻辑
    :param user_ids:
    :param action_type:
    :param is_timely_push:
    :param kwargs:
    :return:
    """
    valid_user_ids = PushService.filter_valid_user_ids(user_ids, kwargs.pop("filter_user_id", 0))
    PushService.push(
        user_ids=valid_user_ids,
        action_type=action_type,
        is_timely_push=is_timely_push,
        **kwargs
    )


@bind('mimas/ctr/push_info/format')
def ctr_push_info_format(content_id, push_type, content_type, tag_name=''):
    """
    个性化 push 封装推送数据
    :param content_id: 推送内容id
    :param push_type: 推送内容类型
    :param content_type: 推送类型枚举
    :param tag_name: 推送关联的标签名字
    :return: 封装好的push数据
    """
    push_info = {}
    try:
        if content_type == PUSH_CONTENT_TYPE.ANSWER:
            push_info = CtrPushContentFormat.ctr_answer(content_id, push_type)

        if content_type == PUSH_CONTENT_TYPE.QUESTION:
            push_info = CtrPushContentFormat.ctr_question(content_id, push_type, tag_name)

        elif content_type == PUSH_CONTENT_TYPE.DIARY:
            push_info = CtrPushContentFormat.ctr_diary(content_id, push_type)

        elif content_type == PUSH_CONTENT_TYPE.TRACTATE:
            push_info = CtrPushContentFormat.ctr_tractate(content_id, push_type)
    except:
        logging_exception()

    return push_info


@bind('mimas/ctr/push_content_ids')
def get_ctr_content_by_ids(content_type, date_object=None):
    """demeter调用，返回按照点击数排序的内容id"""
    result = {
        'content_ids': []
    }
    if not content_type:
        return result

    if not date_object:
        date_object = datetime.now().date() + timedelta(days=-1)

    hot_contents = HotContent.objects.filter(
        date_index=date_object, content_type=content_type
    ).values_list('content_id', 'click_num')

    sorted_contents = sorted(hot_contents, key=lambda item: item[1], reverse=True)
    result['content_ids'] = [data[0] for data in sorted_contents][:30]

    return result
