# -*- coding: utf-8 -*-

from __future__ import absolute_import

from api.models import User, Conversation, Doctor
from api.models.types import MESSAGE_TYPE
from django.core.exceptions import ObjectDoesNotExist
from message.utils.message import send_one_message
from rpc.decorators import bind_context
from rpc.tool.error_code import gen, CODES
from gm_types.msg import CONVERSATION_TYPE


@bind_context('hera/message/send')
def send_message(ctx, user_id, conversation_id=None, target_doctor_id=None, target_user_id=None, content=''):
    user = User.objects.get(id=user_id)
    # 获取收信用户
    try:
        if target_user_id:
            target_user = User.objects.get(pk=target_user_id)
        elif target_doctor_id:
            target_user = Doctor.objects.get(pk=target_doctor_id).user
        else:  # only conversation_id given is not supported currently???
            gen(CODES.MESSAGE_INVALID_TARGET_USER)
    except ObjectDoesNotExist:
        gen(CODES.MESSAGE_INVALID_TARGET_USER)

    content = {'text': content}

    if conversation_id:
        conversation = Conversation.objects.get(pk=conversation_id)
        res = send_one_message(
            send_user=user,
            conversation=conversation,
            conversation_type=CONVERSATION_TYPE.MESSAGE,
            msg_type=MESSAGE_TYPE.TEXT,
            content=content,
            push_stat_labels={'event_type':'push', 'event':'operator_daily'}
        )
    else:
        res = send_one_message(
            send_user=user,
            target_user=target_user,
            conversation_type=CONVERSATION_TYPE.MESSAGE,
            msg_type=MESSAGE_TYPE.TEXT,
            content=content,
            push_stat_labels={'event_type':'push', 'event':'operator_daily'}
        )

    if res['error'] != CODES.SUCCESS:
        gen(res['error'])
