# coding=utf-8
from api.models.tag import Tag
from rpc.decorators import bind, bind_context
from rpc.tool.log_tool import search_logger
from search.utils.tag import search_tag
from rpc.decorators import list_interface


@bind_context("search/tag/esquery")
@list_interface(offset_name='offset', limit_name='size', element_model=Tag)
def search_es_tag(ctx, query='', offset=0, size=5):
    """
    :param query:
    :param offset:
    :param size:
    :return:
        total 匹配结果数量
        id
        icon_url
        name
        description
    """

    ctx.logger.app(search_esquery=dict(type='tag', query=query))

    results = []
    es_data = search_tag(query=query, offset=offset, size=size)
    total = es_data['hits']['total']
    hits = es_data["hits"]["hits"]
    for hit in hits:
        source = {}
        id = hit['_id']
        tag = Tag.objects.get(pk=id)
        try:
            tag = Tag.objects.get(pk=id)
        except Tag.DoesNotExist:
            search_logger.info(u"Tag {} not found".format(id))
            continue

        keys = ['id', 'icon_url', 'name', 'description']
        source = {key: getattr(tag, key) for key in keys}
        highlight = hit.get('highlight', None)
        results.append({
            'source': source,
            'highlight': highlight,
        })

    return {
        'hits': results,
        'total': total
    }