from django.http import HttpResponseBadRequest
from django.views.decorators.http import require_GET
from django.db.models import Q

from staff.lib.decorators import responding_json, available_for_external

from staff.preprofile.repository import Repository
from staff.preprofile.models import ProfileForDepartment


@require_GET
@responding_json
@available_for_external('preprofile.available_preprofile_for_externals')
def suggest_hardware_profile(request):
    department_url = request.GET.get('department_url')
    query = request.GET.get('query', '')

    if not department_url:
        return HttpResponseBadRequest('department_url is required')

    profiles = [{'profile__id': '', 'profile__name': '—', 'profile__comment': ''}] + list(
        ProfileForDepartment.objects
        .filter(department__url=department_url, profile__name__istartswith=query)
        .values('profile__id', 'profile__name', 'profile__comment')
    )

    return [
        {
            'value': profile['profile__id'],
            'label': profile['profile__name'],
            'meta': profile['profile__comment'],
        }
        for profile in profiles
    ]


@require_GET
@responding_json
@available_for_external('preprofile.available_preprofile_for_externals')
def suggest_preprofile(request):
    query = request.GET.get('query', '')

    search_fields = ('first_name', 'first_name_en', 'last_name', 'last_name_en', 'login')

    if not query:
        return []

    qs = Q()
    for word in query.split():
        part_of_qs = Q()
        for search_field in search_fields:
            part_of_qs |= Q(**{search_field + '__istartswith': word})
        qs &= part_of_qs

    preprofiles = Repository(request.user.staff).preprofiles_qs().filter(qs).order_by('-join_at')[:10]

    fields = ('id', 'first_name', 'last_name', 'login')

    return list(preprofiles.values(*fields))
