# coding=utf-8
from __future__ import unicode_literals, absolute_import, print_function
import logging

from django.contrib.auth.models import User

from api.models import Conversation
from api.tool.sms_tool import _send_sms_md, send_sms, get_smart_template_and_platform_id
from api.tool.verification_code import calc_verification_code, get_verification_message
from api.tool.log_tool import logging_exception
from api.tool.user_tool import get_user_from_context

from rpc.decorators import bind, bind_context
from rpc.cache import ViewRecord
from api.models import MESSAGE_TYPE
from sms.utils.smsfactory import send_sms as send_sms_v2
from utils.phone import format_phone


@bind_context('api/private_message/get', login_required=True, deprecated=True)
def user_private_message_get(ctx, conversation_id):
    """
    This interface is DEPREACTED!
    Use message.views.message::conversation_msgs(message/conversation/msgs)
    """
    user = get_user_from_context(ctx)
    conversation = Conversation.objects.get(id=conversation_id)
    target_user = conversation.get_target_user(user)
    messages = conversation.message_set.all().order_by('send_time')
    return {
        'target_uid': target_user.id if target_user else '',
        'user_id': user.id,
        'results': [message.message_detail for message in messages],
    }


@bind("api/send_private_message", deprecated=True)
@bind("api/private_message/send", deprecated=True)
def send_private_message(sender, receiver, message):
    """
    This interface is DEPREACTED!
    Use message.views.message::message_send(message/message/send)
    """
    assert isinstance(sender, int)
    assert isinstance(receiver, int)
    assert isinstance(message, basestring)

    conversation = Conversation.objects.get_conversation(sender, receiver)
    sender = User.objects.get(id=sender)
    conversation.send_message(sender, MESSAGE_TYPE.TEXT, message)


@bind("api/send_short_message")
@bind("api/message/send")
def send_short_message(phone, message, temp_id=None, params=None):
    """
    已废弃

    通用短信发送接口
    :param phone: 手机号码
    :param message: 短信文案
    :param temp_id: 模版id
    :param params: 模版参数
    :return:
    """
    assert isinstance(phone, basestring)
    assert isinstance(message, basestring)
    message = unicode(message) + u'【更美】'
    channel = None if temp_id else 'md'
    send_sms(phone, unicode(message), temp_id, params, channel=channel)


@bind("api/send_verification_code")
@bind("api/verification_code/send")
def send_verification_code(phone):
    """
    发送验证码
    """
    assert isinstance(phone, basestring)
    phone = format_phone(phone)
    try:
        msg_content = u'亲爱的更美用户，您的短信验证码为：%s，有效期：15分钟【更美】'
        verification_code = calc_verification_code(phone)
        code_string = get_verification_message(verification_code)
        logging.info(u"{} verification code is {}".format(phone, code_string))
        template_id, platform = get_smart_template_and_platform_id(phone)
        send_sms_v2(phone, template_id, [{'code': code_string}, {'product': '更美APP'}], platform=platform)
    except:
        logging_exception()
        raise
    return None


@bind("api/verify_verification_code")
@bind("api/verification_code/verify")
def verify_verification_code(phone, verification_code):
    """
    验证验证码
    """
    assert isinstance(phone, basestring)
    assert isinstance(verification_code, basestring)
    answer = "{:04d}".format(calc_verification_code(phone))
    return {u'success': verification_code == answer}


@bind('api/viewrecord/get')
def get_view_record(view_model, item):
    """this api should be deprecated.

    NOTE:
        why we want this hacky close coupled api?
        we need to sperate backend/rpc redis storage, and it has to be this way.
    """
    result = ViewRecord(view_model)[item]
    return result

