from django.db.models import Q
from django_filters import (
    CharFilter,
    FilterSet,
    IsoDateTimeFromToRangeFilter,
    NumberFilter,
)

from verify_trusted.companies.models import Payment


class PaymentFilter(FilterSet):
    company_name_param = CharFilter(
        field_name='company__name',
        lookup_expr='icontains',
    )
    company_id_param = NumberFilter(
        field_name='company__id',
    )
    status = CharFilter(field_name='status')
    user = CharFilter(field_name='company__user__username')
    currency = CharFilter(
        method='currency_filter',
    )
    date = IsoDateTimeFromToRangeFilter(field_name='create_date')

    class Meta:
        model = Payment
        fields = {
            'currency': ['icontains'],
        }

    def user_filter(self, queryset, name, value):
        is_superuser = self.request.user.is_superuser
        if not is_superuser:
            queryset = queryset.filter(id__in=self.request.user.id)
        return queryset

    def currency_filter(self, queryset, name, value):
        queryset = queryset.filter(
            Q(currency=value.upper()) | Q(currency=value.lower())
        )
        return queryset
