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

"""
from django import forms
from django.db.models import QuerySet
from django.utils.translation import gettext_lazy as _
import django_filters

from konova.filters.mixins.office import ConservationOfficeTableFilterMixin
from konova.filters.table_filters import AbstractTableFilter, CheckboxTableFilter, QueryTableFilter


class CheckboxEcoAccountTableFilter(CheckboxTableFilter):
    sr = django_filters.BooleanFilter(
        method='filter_only_show_unrecorded',
        label=_("Show only unrecorded"),
        label_suffix=_(""),
        widget=forms.CheckboxInput(
            attrs={
                "class": "form-check-input",
            }
        )
    )

    def filter_only_show_unrecorded(self, queryset, name, value) -> QuerySet:
        """ Filters queryset depending on value of 'show_recorded' setting

        Args:
            queryset ():
            name ():
            value ():

        Returns:

        """
        if value:
            return queryset.filter(
                recorded=None,
            )
        else:
            return queryset


class SelectionEcoAccountTableFilter(ConservationOfficeTableFilterMixin):
    """ Special selection table filter for eco accounts

    EcoAccounts only need a selection filter for conservation office

    """
    pass


class EcoAccountTableFilter(AbstractTableFilter):
    """ TableFilter for eco accounts

    """
    def __init__(self, user=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.user = user
        qs = kwargs.get("queryset", None)
        request_data = kwargs.get("data", None)

        # Pipe the queryset through all needed filters
        self.selection_filter = SelectionEcoAccountTableFilter(
            data=request_data,
            queryset=qs,
        )
        self.query_filter = QueryTableFilter(
            data=request_data,
            queryset=self.selection_filter.qs,
        )
        self.checkbox_filter = CheckboxEcoAccountTableFilter(
            user=user,
            data=request_data,
            queryset=self.query_filter.qs,
        )
        # Overwrite the final queryset result
        self.qs = self.checkbox_filter.qs
