#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import uuid

from django.conf import settings

from communal.normal_manager import user_manager

from .push_base import (
    push_logger,
    PushServiceBase,
)
from .push_timely import TimelyPushService
from .push_aggregation import AggregationPushService


class PushService(PushServiceBase):
    """
    push service 对外使用的方法
    """

    @staticmethod
    def get_user_all_fans(user_id):
        """
        获取用户的所有粉丝
        :param user_id:
        :return:
        """
        return user_manager.get_user_all_fans(user_id)

    @staticmethod
    def filter_valid_user_ids(user_ids, filter_user_id):
        """
        获取有效的用户id.
        eg: 自己给自己发布的内容点赞,push需要过滤掉自己
        :param user_ids:
        :param filter_user_id:
        :return:
        """
        return [uid for uid in user_ids if uid != filter_user_id]

    @classmethod
    def push(cls, user_ids, action_type, is_timely_push=True, **kwargs):
        """
        对外出口
        :param user_ids:
        :param action_type:
        :param is_timely_push:是否是实时推送
        :param kwargs:
        :return:
        """
        sole_sign = uuid.uuid4().hex  # 唯一标识,目前用来串日志
        push_logger.info(json.dumps({
            "step": 1,
            "sole_sign": sole_sign,
            "resume": "Call the push method. Specific parameters",
            "push_users": user_ids,
            "action_type": action_type,
            "is_timely_push": is_timely_push,
            "other_params": kwargs,
        }))
        # 过滤掉用户 + 自己
        _user_ids = [uid for uid in user_ids if uid not in [settings.SUOZHANG_UID, ]]
        if not _user_ids:
            return

        now = cls.get_now_datetime()
        times_str_dic = cls.current_times(now) or {}  # 获取时间字符串
        # 实时推送
        if is_timely_push:
            # 不在规定时间内  TODO 未来可能会合并到聚合推送
            if not cls.in_push_limit_time(now):
                return

            TimelyPushService.push(
                user_ids=_user_ids,
                action_type=action_type,
                times_str_dic=times_str_dic,
                sole_sign=sole_sign,
                **kwargs
            )

        else:  # 聚合推送
            AggregationPushService.aggregation_push_data(
                user_ids=user_ids,
                action_type=action_type,
                now=now,
                sole_sign=sole_sign,
                **kwargs
            )