"""
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 compensation.models import EcoAccount


class EcoAccountAutocomplete(Select2QuerySetView):
    """ Autocomplete for ecoAccount entries

    Only returns entries that are already recorded and not deleted

    """
    def get_queryset(self):
        if self.request.user.is_anonymous:
            return EcoAccount.objects.none()
        qs = EcoAccount.objects.filter(
            deleted=None,
            recorded__isnull=False,
        ).order_by(
            "identifier"
        )
        if self.q:
            qs = qs.filter(
                Q(identifier__icontains=self.q) |
                Q(title__icontains=self.q)
            ).distinct()
        return qs
