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

from elasticsearch import TransportError
from message.utils.es_abstract import get_esop, get_migrate_esop
from rpc.tool.log_tool import logging_exception, conversation_logger
from . import signals


def sync_conversation(conversation, conversation_extra=None):
    from message.utils.conversation import get_conversation_head_from_conversation, get_conversation_head_bulk_action
    conversation_extra = conversation_extra or {}
    conversation_head = get_conversation_head_from_conversation(
        conversation,
        conversation_extra)
    action = get_conversation_head_bulk_action(conversation_head)
    get_esop().bulk_single(action)


@signals.post_create_conversation.connect
def post_create_conversation(conversation, conversation_extra):
    sync_conversation(conversation, conversation_extra)


@signals.post_touch_conversation.connect
def post_touch_conversation(user, conversation):
    sync_conversation(conversation)


@signals.post_send_message.connect
def post_send_message(conversation):
    sync_conversation(conversation)
