from __future__ import unicode_literals, absolute_import, print_function

from gm_protocol import GmProtocol
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, tractate_favor_count_cache
from talos.services.soft_article.soft_article import SoftArticleService
from talos.services.soft_article.favor import SoftArticleFavorService
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 talos.services.user import UserService


class Test():
    pass


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

    soft_article = SoftArticleService.healthy(soft_article_id)
    soft_article_favor = SoftArticleFavorService.create(user_id=user.id, softarticle_id=soft_article.id)
    doctor_user_id = UserService.get_user_id_by_doctor_id(doctor_id=soft_article.doctor_id)
    # favor_tool = FavorTool(redis_c=favor_cache, user_id=doctor_user_id)
    # favor_tool.receive_soft_article_favor(soft_article_favor.id)

    favor_num = SoftArticleService.inc_soft_article_favor(softarticle_id=soft_article.id)

    return {
        "favor_amount": favor_num
    }


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

    soft_article = SoftArticleService.healthy(soft_article_id)
    soft_article_favor = SoftArticleFavorService.cancel(user_id=user.id, softarticle_id=soft_article.id)

    favor_num = SoftArticleService.dec_soft_article_favor(softarticle_id=soft_article.id)

    doctor_user_id = UserService.get_user_id_by_doctor_id(doctor_id=soft_article.doctor_id)
    # favor_tool = FavorTool(redis_c=favor_cache, user_id=doctor_user_id)
    # favor_tool.remove_soft_article_favor(soft_article_favor_id=soft_article_favor.id)

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


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

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


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

    SoftArticleFavorService.tractate_favorite_read(user_id=user.id)

    return gen(CODES.SUCCESS)

