from __future__ import unicode_literals, absolute_import, print_function

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

from qa.utils.decorator import listing
from talos.cache.base import favor_cache
from talos.services.tractate import TractateFavorService, TractateService
from talos.tools.favor_tool import FavorTool
from talos.views.tractate import update_tractate_special_info
from utils.rpc import gen, get_current_user
from utils.push import push_task_to_user_multi
from utils.stat_log import SocialStatLogForUserAction


@bind('mimas/tractate_favor/create')
def tractate_favorite_create(tractate_id):
    """
    新帖子收藏
    :param tractate_id:
    :return:
    """
    user = get_current_user()
    if not user:
        return gen(CODES.LOGIN_REQUIRED)

    tractate = TractateService.healthy(tractate_id)
    tractate_favor, created = TractateFavorService.create(user_id=user.id, tractate=tractate)
    if not created:
        return {
            "favor_amount": tractate.favor_amount
        }

    favor_tool = FavorTool(redis_c=favor_cache, user_id=tractate.user_id)
    favor_tool.receive_tractate_favor(tractate_favor.id)

    favor_num = TractateService.inc_tractate_favor(tractate)

    push_url = GmProtocol().get_tractate_detail(
        tractate_id=tractate.id,
        tractate_detail_from=LIST_TRACTATE_FROM.NOTICE_FAVOR
    )
    push_task_to_user_multi(
        user_ids=[tractate.user_id],
        extra={
            'type': PUSH_INFO_TYPE.GM_PROTOCOL,
            'pushUrl': push_url,
            'push_url': push_url,
        },
        push_type=AUTOMATED_PUSH.TRACTATE_IS_COLLECTED,
        alert=u'{user_name}收藏了你的帖子{content}'.format(
            user_name=str(user.nick_name), content=tractate.content[:10])
    )

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

    return {
        "favor_amount": favor_num
    }


@bind('mimas/tractate_favor/cancel')
def tractate_favorite_cancel(tractate_id):
    """
    取消收藏
    :param tractate_id:
    :return:
    """
    user = get_current_user()
    if not user:
        return gen(CODES.LOGIN_REQUIRED)

    tractate = TractateService.healthy(tractate_id)
    tractate_favor, cancel_status = TractateFavorService.cancel(user_id=user.id, tractate=tractate)
    if not cancel_status:
        return {
            "favor_amount": tractate.favor_amount
        }

    favor_num = TractateService.dec_tractate_favor(tractate)

    favor_tool = FavorTool(redis_c=favor_cache, user_id=tractate.user_id)
    favor_tool.remove_tractate_favor(tractate_favor_id=tractate_favor.id)

    return {
        "favor_amount": favor_num if favor_num >= 0 else 0
    }


@bind('mimas/tractate/favors')
@listing()
def tractate_favorite(start_num=0, count=10):
    """
    获取我的收藏列表
    :param start_num:
    :param offset:
    :return:
    """
    user = get_current_user()
    if not user:
        return gen(CODES.LOGIN_REQUIRED)

    tractate_list = []
    tractate_ids = TractateFavorService.tractate_favorite_list(user_id=user.id, start_num=start_num, count=count)

    if tractate_ids:
        tractates_info_dic = TractateService.get_tractate_infos_by_ids(tractate_ids=tractate_ids, need_special_info=True)
        tractate_list = tractates_info_dic.get("tractate_list", [])
        tractate_list = update_tractate_special_info(tractate_list, tractate_ids, user.id)
        TractateService.tractate_view_increase_num(tractates_info_dic.get("valid_tractate_ids", []))
    return tractate_list


@bind('mimas/tractate_favor/unread')
def tractate_favorite_unread():
    """
    获取用户未读状态的收藏数
    :return:
    """
    user = get_current_user()
    if not user:
        return gen(CODES.LOGIN_REQUIRED)

    count = TractateFavorService.get_unread_favorite_num(user_id=user.id)
    return {'count': count}


@bind('mimas/tractate_favor/read_all')
def tractate_favorite_read():
    user = get_current_user()
    if not user:
        return gen(CODES.LOGIN_REQUIRED)

    TractateFavorService.tractate_favorite_read(user_id=user.id)

    return gen(CODES.SUCCESS)
