from django.contrib.auth import get_user_model
from django.db.models import Q
from django.urls import reverse
from django.utils.translation import gettext_lazy as _

from shared import autocomplete

User = get_user_model()


class COFMemberSearch(autocomplete.ModelSearch):
    model = User
    search_fields = ["username", "first_name", "last_name"]
    verbose_name = _("Membres du COF")

    def get_queryset_filter(self, *args, **kwargs):
        qset_filter = super().get_queryset_filter(*args, **kwargs)
        qset_filter &= Q(profile__is_cof=True)
        return qset_filter

    def result_uuid(self, user):
        return user.username

    def result_link(self, user):
        return reverse("user-registration", args=(user.username,))


class COFOthersSearch(autocomplete.ModelSearch):
    model = User
    search_fields = ["username", "first_name", "last_name"]
    verbose_name = _("Non-membres du COF")

    def get_queryset_filter(self, *args, **kwargs):
        qset_filter = super().get_queryset_filter(*args, **kwargs)
        qset_filter &= Q(profile__is_cof=False)
        return qset_filter

    def result_uuid(self, user):
        return user.username

    def result_link(self, user):
        return reverse("user-registration", args=(user.username,))


class COFLDAPSearch(autocomplete.LDAPSearch):
    def result_link(self, clipper):
        return reverse("clipper-registration", args=(clipper.clipper, clipper.fullname))


class COFAutocomplete(autocomplete.Compose):
    search_units = [
        ("members", COFMemberSearch()),
        ("others", COFOthersSearch()),
        ("clippers", COFLDAPSearch()),
    ]


cof_autocomplete = COFAutocomplete()
