from django.conf import settings
from gm_types.gaia import SUBSCRIPT_ARTICLE_SORT
from libs.es import es_query


def gen_query(query):
    fields = ["tag_names", "title"]
    m = {
        'query': query,
        'type': 'cross_fields',
        # 'operator': 'and',
        'fields': fields,
    }
    return {"multi_match": m}


def gen_sorting(sort_type, sort_params={}):
    sort = []

    if sort_type == SUBSCRIPT_ARTICLE_SORT.ORDERING:
        sort += [
            {'ordering': {'order': 'desc'}}
        ]
    elif sort_type == SUBSCRIPT_ARTICLE_SORT.CREATE_TIME:
        sort += [
            {'create_time_val': {'order': 'desc'}}
        ]

    return sort


def get_filters(filters):

    f = []

    if not filters:
        return f

    def list_ids(v):
        l = None
        if v and isinstance(v, list):
            l = v
        elif v:
            l = [v]
        return l

    for k, v in filters.items():
        if k == 'tag_ids' and isinstance(v, list) and v:

            ids = list_ids(v)
            if not ids: continue

            f.append({'terms': {'tags': ids}})

        elif k == 'category_id':

            ids = list_ids(v)
            if not ids: continue

            f.append({'terms': {'categories': ids}})
        else:
            f.append({'term': {k: v}})

    return f


def recall_subscript_article(query, sort_type, filters={}, offset=0, size=10):

    size = min(size, settings.COUNT_LIMIT)

    f = get_filters(filters)
    filtered = {
        "filter": {
            "bool": {
                "must": f,
            }
        }
    }

    if query:
        filtered['query'] = gen_query(query)

    q = {
        "_source": {
            "include": ["id"],
        },
        "query": {
            "filtered": filtered
        },
        "sort": gen_sorting(sort_type)
    }

    res = es_query('subscript_article', q, offset, size)
    hits = res["hits"]["hits"]
    hit_ids = [hit["_source"] for hit in hits]

    return hit_ids
