from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.db.models import Q
from django.http import Http404
from django.views.generic import TemplateView

from shared.views import autocomplete

User = get_user_model()


class KfetAccountSearch(autocomplete.ModelSearch):
    model = User
    search_fields = [
        "username",
        "first_name",
        "last_name",
        "profile__account_kfet__trigramme",
    ]

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


class COFMemberSearch(autocomplete.ModelSearch):
    model = User
    search_fields = ["username", "first_name", "last_name"]

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


class OthersSearch(autocomplete.ModelSearch):
    model = User
    search_fields = ["username", "first_name", "last_name"]

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


class KfetAutocomplete(autocomplete.Compose):
    search_units = [
        ("kfet", "username", KfetAccountSearch),
        ("users_cof", "username", COFMemberSearch),
        ("users_notcof", "username", OthersSearch),
        ("clippers", "clipper", autocomplete.LDAPSearch),
    ]


kfet_autocomplete = KfetAutocomplete()


class AccountCreateAutocompleteView(PermissionRequiredMixin, TemplateView):
    template_name = "kfet/account_create_autocomplete.html"
    permission_required = "kfet.is_team"

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        if "q" not in self.request.GET:
            raise Http404
        q = self.request.GET["q"]
        ctx["q"] = q
        results = kfet_autocomplete.search(q.split())
        ctx["options"] = sum((len(res) for res in results.values()))
        ctx.update(results)
        return ctx


class AccountSearchAutocompleteView(PermissionRequiredMixin, TemplateView):
    template_name = "kfet/account_search_autocomplete.html"
    permission_required = "kfet.is_team"

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        if "q" not in self.request.GET:
            raise Http404
        q = self.request.GET["q"]
        ctx["q"] = q
        ctx["accounts"] = [
            (user.profile.account_kfet.trigramme, user.get_full_name())
            for user in KfetAccountSearch().search(q.split())
        ]
        return ctx
