"""
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.widgets import ModelSelect2
from django.utils.translation import gettext_lazy as _
import django_filters

from codelist.models import KonovaCode
from codelist.settings import CODELIST_CONSERVATION_OFFICE_ID, CODELIST_REGISTRATION_OFFICE_ID


class ConservationOfficeTableFilterMixin(django_filters.FilterSet):
    """ A mixin for AbstractTableFilter

    Specialized on filtering for related conservation offices

    """
    co = django_filters.ModelChoiceFilter(
        method="filter_cons_office",
        label=_(""),
        label_suffix=_(""),
        queryset=KonovaCode.objects.filter(
            is_archived=False,
            is_leaf=True,
            code_lists__in=[CODELIST_CONSERVATION_OFFICE_ID],
        ),
        widget=ModelSelect2(
            url="codelist:conservation-office-autocomplete",
            attrs={
                "data-placeholder": _("Conservation office"),
                "title": _("Search for conservation office"),
                "class": "",
            }
        ),
    )

    def filter_cons_office(self, queryset, name, value):
        qs = queryset.filter(
            responsible__conservation_office=value
        )
        return qs


class RegistrationOfficeTableFilterMixin(django_filters.FilterSet):
    """ A mixin for AbstractTableFilter

    Specialized on filtering for related registration offices

    """
    ro = django_filters.ModelChoiceFilter(
        method="filter_reg_office",
        label=_(""),
        label_suffix=_(""),
        queryset=KonovaCode.objects.filter(
            is_archived=False,
            is_leaf=True,
            code_lists__in=[CODELIST_REGISTRATION_OFFICE_ID],
        ),
        widget=ModelSelect2(
            url="codelist:registration-office-autocomplete",
            attrs={
                "data-placeholder": _("Registration office"),
                "title": _("Search for registration office"),
                "class": "",
            }
        ),
    )

    def filter_reg_office(self, queryset, name, value):
        qs = queryset.filter(
            responsible__registration_office=value
        )
        return qs
