# coding=utf8
from __future__ import unicode_literals, absolute_import, print_function

from gm_types.gaia import QUESTION_ORDER_TYPE

from rpc.context import get_rpc_remote_invoker
from rpc.decorators import bind_context
from search.utils.question import search_question


@bind_context("search/question/esquery")
def search_es_diary(ctx, query='', offset=0, size=5, sort_type=QUESTION_ORDER_TYPE.DEFAULT, filters={}):
    ctx.logger.app(search_esquery=dict(type='question', query=query))
    rpc_client = get_rpc_remote_invoker()

    results = []
    es_data = search_question(query=query, offset=offset, size=size, sort_type=sort_type, filters=filters)
    related_ids = es_data['question_ids']

    question_ids = [related['question'] for related in related_ids if related['question']]
    answer_ids = [related['answer'] for related in related_ids if related['answer']]

    questions = rpc_client['qa/question/list_for_es'](pks=question_ids)
    answers = rpc_client['qa/answer/list_for_es'](pks=answer_ids)
    questions = questions.unwrap()
    answers = answers.unwrap()

    for question in related_ids:

        if question['answer']:
            answer = answers.get(str(question['answer']))
            if not answer:
                continue

            if question['answer_highlight']:
                question['answer_highlight'] = question['answer_highlight'].replace('<ems>', '')
                question['answer_highlight'] = question['answer_highlight'].replace('</ems>', '')
                answer['content'] = question['answer_highlight']
            results.append(answer)

        elif question['question']:
            question = questions.get(str(question['question']))
            if not question:
                continue

            results.append(question)

    return results
