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

from gm_types.doris import INTERPOSE_TYPE

from rpc.all import get_rpc_remote_invoker
from rpc.tool.log_tool import logging_exception


def get_interpose(offset,size, keyword, filters, sort_type, interpose_type):
    tag_ids = []
    city_tag_id = None
    for k, v in filters.items():
        if k == 'area_tag_id' and isinstance(v, (long, int)):
            city_tag_id = v
        elif k == 'tag_ids' and isinstance(v, list) and v:
            tag_ids = v
        elif k == 'bodypart_tag_id':
            if isinstance(v, list) and v:
                tag_ids = v
            elif isinstance(v, (int, long)):
                tag_ids.append(v)
    if len(tag_ids) > 1:
        return None

    try:
        rpc_invoker = get_rpc_remote_invoker()
        result = rpc_invoker['doris/interpose/get'](
            interpose_type=interpose_type,
            city_tag_id=city_tag_id,
            tag_id=tag_ids[0] if tag_ids else None,
            sort_order=sort_type,
            keyword=keyword,
        ).unwrap()
        if result:
            result = result[offset:offset+size]
    except:
        logging_exception()
        return None
    return result


def search_interpose(offset, size, keyword, filters, sort_type):
    '''
    '''
    try:
        diary_ids = get_interpose(offset, size, keyword, filters, sort_type, INTERPOSE_TYPE.DIARY_SEARCH)
        if not diary_ids:
            return None
        res = {
            'hits': {
                'total': len(diary_ids)
            },
        }
        hits = []
        for diary_id in diary_ids:
            hit = {
                '_source': {},
                '_id': diary_id,
            }
            hits.append(hit)
        res['hits']['hits'] = hits
        return res
    except:
        logging_exception()


def filter_interpose(offset, size, keyword, filters, sort_type):
    try:
        diary_ids = get_interpose(offset, size, keyword, filters, sort_type, INTERPOSE_TYPE.DIARY_FILTER)
        if not diary_ids:
            return None
        res = {
            'diary_ids': diary_ids,
            'total': len(diary_ids)
        }
        return res
    except:
        logging_exception()
