# coding: utf-8


from gm_types.gaia import DIARY_ORDER_TYPE
from gm_types.push import PUSH_INFO_TYPE, PERSONAL_PUSH_TYPE

from rpc.tool.protocol import PushUrlProtocol, gm_protocol
from talos.models.diary import Diary

from api.tool.log_tool import logging_exception
from api.tool.user_tool import (
    get_doctor_by_user_id,
    get_username_with_title,
)
from search.utils.diary import filter_diary

from rpc.context import get_rpc_remote_invoker
from talos.tools.push_tool import limit_push

def get_diary_by_id(diary_id):
    """
    NOTE:
        根据diary_id获取diary信息
    :return:
    """
    try:
        diary = Diary.objects.get(id=diary_id)
        return diary
    except Diary.DoesNotExist:
        return None


def push_diary_reply_message(user, diary, content, replied_reply, push_type=PERSONAL_PUSH_TYPE.REPLY):
    """
    NOTE:
        异步进行消息提醒
    :param user:
    :param diary:
    :param content:
    :param replied_reply: 被回复的TopicReply 消息对象
    :return:
    """
    try:
        if len(content) > 50:
            content = content[:50] + u'...'
        reply_username = get_username_with_title(user.id)
        msg = u'%s 回复你：%s' % (reply_username, content)

        receive_msg_user_ids = []

        if replied_reply:
            if user and user.id != replied_reply.user_id:
                receive_msg_user_ids.append(replied_reply.user_id)
        else:
            if user and user.id != diary.user_id:
                receive_msg_user_ids.append(diary.user_id)

        platform = ['android', 'iPhone']

        for receive_msg_user_id in set(receive_msg_user_ids):
            if limit_push(user.id, push_type):
                extra = {
                    'type': PUSH_INFO_TYPE.GM_PROTOCOL,
                    'msgType': 4,
                    'pushUrl': gm_protocol.comment_list,
                    'push_url': gm_protocol.comment_list
                }
                rpc_invoker = get_rpc_remote_invoker()
                try:
                    rpc_invoker['push2/push/user/notification/uids'](
                        user_ids=[receive_msg_user_id],
                        platform=platform,
                        alert=u'%s刚才评论了你的内容～快去看看ta是不是夸你美～' % reply_username,
                        extra=extra,
                        labels={'event_type':'push', 'event':'received_comments'}
                    ).unwrap()
                except:
                    logging_exception()

            # if receiver is a doctor, push to doctor client
            recv_doctor = get_doctor_by_user_id(receive_msg_user_id)
            if recv_doctor:
                extra = {
                    'type': PUSH_INFO_TYPE.GM_PROTOCOL,
                    'pushUrl': PushUrlProtocol.DOCTOR_COMMENT_LIST,
                }
                rpc_invoker = get_rpc_remote_invoker()
                rpc_invoker['push2/push/doctor/notification/doctor_ids'](
                    doctor_ids=[recv_doctor.id],
                    platform=platform,
                    extra=extra,
                    alert=msg,
                ).unwrap()
    except:
        logging_exception()


def get_diaries_by_tags(tag_ids, offset=0, size=10,
                        sort_type=DIARY_ORDER_TYPE.HOT):
    filters = {'tag_ids': tag_ids}
    diaries_info = filter_diary(
        offset=offset, size=size, sort_type=sort_type, filters=filters
    )
    ids = diaries_info['diary_ids']
    diaries = []
    if ids:
        diaries = get_rpc_remote_invoker()['diary/list_data_get_by_ids'](ids=ids).unwrap()
        diaries = [
            {
                'diary_id': diary.get('id'),
                'diary_cover': (
                    diary['images'][1]['image']
                    if len(diary.get('images')) > 1
                    else ''
                ),
                'diary_vote_num': diary.get('vote_num'),
                'content': diary.get('content'),
                'tags': diary.get('tags'),
                'images': diary.get('images'),

            } for diary in diaries.get('diaries')
        ]
    return diaries

