# -*- coding: utf8 -*-

from __future__ import unicode_literals, absolute_import, print_function

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

from talos.cache.base import favor_cache
from talos.models.diary import Diary, DiaryFavor
from talos.services import get_user_from_context
from talos.manager.diary import diary_list_manager
from talos.decorators import list_interface
from talos.rpc import bind_context
from talos.tools.favor_tool import FavorTool
from utils.rpc import gen, rpc_client, logging_exception, get_current_user
from utils.push import limit_push, push_task_to_user_multi
from utils.stat_log import SocialStatLogForUserAction


@bind('diary/favorite/create')
def api_diary_favorite_create(diary_id):
    """
    收藏一个日记本
    :param diary_id:
    :return:
    """
    user = get_current_user()
    if not user:
        return gen(CODES.LOGIN_REQUIRED)
    try:
        diary = Diary.objects.get(pk=diary_id)
    except Diary.DoesNotExist:
        return gen(CODES.DIARY_NOT_FOUND)

    df, _ = DiaryFavor.objects.get_or_create(user_id=user.id, diary_id=diary.id)
    if df.is_deleted:
        df.is_deleted = False
        df.unread = True
        df.save()

    favor_tool = FavorTool(redis_c=favor_cache, user_id=diary.user_id)
    favor_tool.receive_diary_favor(df.id)

    pushUrl = GmProtocol().get_diary_detail(id=diary.id)
    push_task_to_user_multi(
        user_ids=[diary.user_id],
        extra={
            'type': PUSH_INFO_TYPE.GM_PROTOCOL,  # 推送信息类型
            'pushUrl': pushUrl,
            'push_url': pushUrl,
        },
        push_type=AUTOMATED_PUSH.DIARY_IS_SUBSCRIBED,
        alert=u'{user_name} 收藏了你的日记本【{diary_title}】，美丽值 upup！'.format(user_name=str(user.nick_name), diary_title=diary.title)
    )

    # 用户行为埋点，收藏相关
    SocialStatLogForUserAction.stat_log_for_favor(
        content_type=SocialStatLogForUserAction.CONTENT_TYPE.diary,
        user_id=user.id,
        content_id=diary_id
    )


@bind('diary/favorite/delete')
def api_diary_favorite_delete(diary_id):
    """
    取消收藏日记本
    :param diary_id:
    :return:
    """
    user = get_current_user()
    if not user:
        return gen(CODES.LOGIN_REQUIRED)
    diary = Diary.objects.get(pk=diary_id)
    df = DiaryFavor.objects.filter(user_id=user.id, diary=diary).first()
    if df:
        df.is_deleted=True
        df.unread=False
        df.save()
        favor_tool = FavorTool(redis_c=favor_cache, user_id=diary.user_id)
        favor_tool.remove_diary_favor(df.id)


@bind('diary/favorite/get')
@list_interface(offset_name='start_num', limit_name='count', element_model=Diary,
                element_func_list=[Diary.get_diary_info])
def api_diary_favorite_get(count=10, start_num=0):
    """
    获取我的收藏
    :param count:
    :param start_num:
    :return:
    """
    user = get_current_user()
    if not user:
        return gen(CODES.LOGIN_REQUIRED)

    favors = DiaryFavor.objects.select_related('diary')
    favors = favors.filter(
        user_id=user.id, is_deleted=False, diary__is_online=True,
    ).order_by('-id')[start_num: start_num + count]
    diary_objs = [f.diary for f in favors]

    return diary_list_manager.get_diary_list_by_diary_objs(diary_objs, viewer_user_id=user.id)


@bind("diary/read_favors")
def diary_favors_read():

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

    diary_ids = list(Diary.objects.filter(user_id=user.id).values_list("id", flat=True))
    DiaryFavor.objects.filter(
        diary_id__in=diary_ids,
        is_deleted=False,
        unread=True
    ).update(unread=False)


@bind('diary/has_favored')
def diary_has_favored(diary_id, user_id):
    """用户是否收藏过日记本"""
    query = DiaryFavor.objects.filter(diary_id=diary_id, user_id=user_id, is_deleted=False)
    has_favored = query.exists()
    return {'has_favored': bool(has_favored)}