"""
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 user.models import User, Team


class ShareUserAutocomplete(Select2QuerySetView):
    """ Autocomplete for share with single users


    """
    def get_queryset(self):
        qs = User.objects.none()
        if self.request.user.is_anonymous:
            return qs
        if self.q:
            qs = User.objects.all()
            # Due to privacy concerns only a full username match will return the proper user entry
            qs = qs.filter(
                Q(username=self.q) |
                Q(email=self.q)
            ).distinct()
        qs = qs.order_by("username")
        return qs

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

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


class ShareTeamAutocomplete(Select2QuerySetView):
    """ Autocomplete for share with teams

    """
    def get_queryset(self):
        qs = Team.objects.none()
        if self.request.user.is_anonymous:
            return qs
        if self.q:
            qs = Team.objects.filter(
                deleted__isnull=True
            )
            q_parts = self.q.split(" ")
            q = Q()
            for part in q_parts:
                q &= Q(name__icontains=part)
            qs = qs.filter(q)
        qs = qs.order_by(
            "name"
        )
        return qs

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

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