"""
Author: Michel Peltriaux
Organization: Struktur- und Genehmigungsdirektion Nord, Rhineland-Palatinate, Germany
Contact: michel.peltriaux@sgdnord.rlp.de
Created on: 29.07.21

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

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


class SelectionCompensationTableFilter(SelectionTableFilter):
    """ Specialization of regular SelectionTableFilter for compensation model

    """
    def filter_reg_office(self, queryset, name, value):
        return queryset.filter(
            intervention__responsible__registration_office=value
        )

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


class QueryCompensationTableFilter(QueryTableFilter):
    """ Specialization of regular QueryTableFilter for compensation model

    """
    def filter_file_number(self, queryset, name, value) -> QuerySet:
        queryset = queryset.filter(
            Q(intervention__responsible__registration_file_number__icontains=value) |
            Q(intervention__responsible__conservation_file_number__icontains=value)
        )
        return queryset


class CheckboxCompensationTableFilter(CheckboxTableFilter):
    """ Specialization of regular CheckboxTableFilter for compensation model

    """

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

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

        Returns:

        """
        if not value:
            return queryset.filter(
                Q(intervention__users__in=[self.user]) |  # requesting user has access
                Q(intervention__teams__in=self.user.shared_teams)
            ).distinct()
        else:
            return queryset

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

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

        Returns:

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


class CompensationTableFilter(AbstractTableFilter):
    """ TableFilter for compensations

    Based widely on InterventionTableFilter.
    Just some minor changes for Compensation model.

    """
    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)

        # Overwrite all filters for special needs of compensations
        self.selection_filter = SelectionCompensationTableFilter(
            data=request_data,
            queryset=qs,
        )
        self.query_filter = QueryCompensationTableFilter(
            data=request_data,
            queryset=self.selection_filter.qs,
        )
        self.checkbox_filter = CheckboxCompensationTableFilter(
            user=user,
            data=request_data,
            queryset=self.query_filter.qs,
        )
        # Overwrite final queryset as well
        self.qs = self.checkbox_filter.qs


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
