# coding=utf-8

from __future__ import unicode_literals, absolute_import, print_function

from gm_protocol import GmProtocol
from gm_types.error import ERROR as CODES
from gm_types.gaia import TOPIC_TYPE
from gm_types.push import PERSONAL_PUSH_TYPE, PUSH_INFO_TYPE, AUTOMATED_PUSH
from gm_rpcd.all import bind

from talos.cache.base import favor_cache
from talos.decorators import list_interface
from talos.manager.topic import topic_list_manager
from talos.models.topic import Problem
from talos.models.topic import ProblemFavor
from talos.services import get_user_from_context
from talos.tools.favor_tool import FavorTool
from utils.push import limit_push, push_task_to_user_multi
from utils.rpc import gen, logging_exception, get_current_user
from utils.stat_log import SocialStatLogForUserAction


@bind("topic/topics_favor_my")
# @bind_context("topic/my_favor_list")
@list_interface(offset_name='start_num', limit_name='count', element_model=Problem)
def get_topics_favor_my(count=10, start_num=0):
    """我收藏的话题列表
       count: 每次请求记录条数, 默认为10
       start_num: 起始条数, 默认为0
    """
    user = get_current_user()
    if not user:
        return gen(CODES.LOGIN_REQUIRED)
    favors = ProblemFavor.objects.filter(user_id=user.id, is_deleted=False)
    favors = favors.order_by("-id")[start_num:start_num + count]

    topic_ids = [f.problem_id for f in favors]
    result = topic_list_manager.get_list_data_by_topic_ids(topic_ids, user.id)
    return result


@bind("topic/read_favors")
def topics_favors_read():

    user = get_current_user()
    if not user:
        return gen(CODES.LOGIN_REQUIRED)

    topic_ids = list(Problem.objects.filter(user_id=user.id).values_list("id", flat=True))
    ProblemFavor.objects.filter(
        problem_id__in=topic_ids,
        is_deleted=False,
        unread=True
    ).update(unread=False)


# @bind_context('topic/favorite/create')
# @bind_context('topic/favorite_create')
# def api_topic_favorite_create(topic_id):
#     """
#     收藏一个帖子
#     """
#     user = get_user_from_context()
#     try:
#         topic = Problem.objects.get(pk=topic_id)
#     except Problem.DoesNotExist:
#         return gen(CODES.TOPIC_NOT_FOUND)
#
#     pf, _ = ProblemFavor.objects.get_or_create(user_id=user.id, problem_id=topic.id)
#     if pf.is_deleted:
#         pf.is_deleted = False
#         pf.save()


# @bind_context('topic/favorite/delete')
# @bind_context('topic/favorite_delete')
# def api_topic_favorite_delete(topic_id):
#     """
#     取消收藏帖子
#     """
#     user = get_user_from_context()
#     topic = Problem.objects.get(pk=topic_id)
#     ProblemFavor.objects.filter(user_id=user.id, problem_id=topic.id).update(is_deleted=True)


@bind('topic/user_favor/delete')
def delete_user_favor(problem_id):
    user = get_current_user()
    if not user:
        return gen(CODES.LOGIN_REQUIRED)

    try:
        problem = Problem.objects.get(id=problem_id)
    except Problem.DoesNotExist:
        return gen(CODES.TOPIC_NOT_FOUND)

    pf = ProblemFavor.objects.filter(user_id=user.id, problem_id=problem.id).first()
    if pf:
        pf.is_deleted=True
        pf.save()

        favor_tool = FavorTool(redis_c=favor_cache, user_id=problem.user_id)
        favor_tool.receive_topic_favor(pf.id)

    return None


@bind('topic/user_favor/get_or_create')
def get_or_create_user_favor(problem_id):
    user = get_current_user()
    if not user:
        return gen(CODES.LOGIN_REQUIRED)

    try:
        problem = Problem.objects.get(id=problem_id)
    except Problem.DoesNotExist:
        logging_exception()
        return gen(CODES.TOPIC_NOT_FOUND)
    pf, _ = ProblemFavor.objects.get_or_create(user_id=user.id, problem_id=problem.id)
    if pf.is_deleted:
        pf.is_deleted = False
        pf.save()

    favor_tool = FavorTool(redis_c=favor_cache, user_id=problem.user_id)
    favor_tool.receive_topic_favor(pf.id)

    pushUrl = GmProtocol().get_topic_detail(id=problem_id)
    push_task_to_user_multi(
        user_ids=[problem.user_id],
        extra={
            'type': PUSH_INFO_TYPE.GM_PROTOCOL,  # 推送信息类型
            'pushUrl': pushUrl,
            'push_url': pushUrl,
        },
        push_type=AUTOMATED_PUSH.JOURNAL_POST_IS_COLLECTED,
        alert=u'{user_name} 收藏了你的日记贴，再接再厉哦~'.format(user_name=str(user.nick_name))
    )

    _topic_type = problem.topic_type
    if _topic_type in [TOPIC_TYPE.ASK, TOPIC_TYPE.SHARE, TOPIC_TYPE.TOPIC]:  # 日记帖
        # 用户行为埋点，收藏相关
        SocialStatLogForUserAction.stat_log_for_favor(
            content_type=SocialStatLogForUserAction.CONTENT_TYPE.diary,
            user_id=user.id,
            content_id=problem.diary_id,
        )
