from urllib.parse import quote
from django.conf import settings
from intranet.search.core.storages import ProfileStorage
from intranet.search.admin import template


def profile_list(request, entity):
    profiles = settings.ISEARCH['profiles']
    from_ = request.GET.get('from', '')
    page = int(request.GET.get('page', '0'))
    key = request.GET.get('id', '').strip()

    st = ProfileStorage()
    PER_PAGE = 100

    if key:
        data = list(filter(None, [st.get(entity, key)]))
        count = len(data)
    else:
        data = st.list_all(entity, from_, PER_PAGE)
        count = st.count(entity)

        data = list(data)

    names = {i for item in data for i in item} - {'_id'}

    if data and (page + 1) * PER_PAGE < count:
        next_ = quote(data[-1]['_id'])
    else:
        next_ = None

    if names:
        names = ['_id'] + sorted(names)

    return template.render(
        request=request,
        template='isearch/profile/list.html',
        context={
            'names': names,
            'items': data,
            'entity': entity,
            'entities': profiles,
            'next': next_,
            'page_number': page + 1,
            '_id': key,
        },
        content_type='text/html',
    )
