"""
Author: Michel Peltriaux
Organization: Struktur- und Genehmigungsdirektion Nord, Rhineland-Palatinate, Germany
Contact: ksp-servicestelle@sgdnord.rlp.de
Created on: 18.08.22

"""
from dal_select2.views import Select2QuerySetView
from django.db.models import Q

from intervention.models import Intervention


class InterventionAutocomplete(Select2QuerySetView):
    """ Autocomplete for intervention entries

    Only returns entries that are accessible for the requesting user

    """
    def get_queryset(self):
        user = self.request.user
        if user.is_anonymous:
            return Intervention.objects.none()
        qs = Intervention.objects.filter(
            Q(deleted=None) &
            Q(users__in=[user]) |
            Q(teams__in=user.teams.all())
        ).order_by(
            "identifier"
        ).distinct()
        if self.q:
            qs = qs.filter(
                Q(identifier__icontains=self.q) |
                Q(title__icontains=self.q)
            ).distinct()
        return qs

    def get_result_label(self, result):
        return str(result)

    def get_selected_result_label(self, result):
        return str(result)
