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

from django.conf import settings
import functools
from api.models import Tag
from collections import deque, OrderedDict


limited_size = functools.partial(min, settings.COUNT_LIMIT)
"""
def limited_size(size):
    return min(settings.COUNT_LIMIT, size)
"""


def area_tag_id_filter(prefix_list, value):
    return {
        'bool': {
            'should': [
                {'term': {prefix + field: value}}
                for prefix in prefix_list
                for field in [
                    'city_tag_id',
                    'city_province_tag_id',
                    'city_province_country_tag_id',
                ]
            ]
        }
    }


def get_query_matched_tags(query):
    query = query.strip()
    tags = Tag.objects.filter(name__exact=query)
    if len(tags) > 0:
        return list(tags)
    else:
        return []


def variousness(items, variety_size):
    src = deque(items)
    dst = []
    while len(src) > 0:
        pos, temp, recover, dup = 0, [], [], []
        while pos < variety_size:
            try:
                item = src.popleft()
                if item.get("group") in dup:
                    recover.append(item)
                else:
                    temp.append(item)
                    dup.append(item.get("group"))
                    pos += 1
            except IndexError:
                diff = variety_size - pos
                diff, remain = recover[:diff], recover[diff:]
                temp.extend(diff)
                recover = remain
                break
        multi = OrderedDict()
        for key in dup:
            multi[key] = []
        for item in temp:
            multi[item.get("group")].append(item)
        temp = filter(lambda a: a != None, itertools.chain.from_iterable(itertools.izip_longest(*multi.values())))

        dst.extend(temp)
        src.extendleft(reversed(recover))

    return dst

