from __future__ import absolute_import

from django import forms
from django_filters import filters
from django_filters import filterset

from core import models
from core.utils import blackbox


class RewardFilterByLogin(filters.Filter):
    field_class = forms.CharField

    def filter(self, qs, value):
        if value:
            user = blackbox.external_userinfo_by_login(value)
            reporter = models.Reporter.objects.get(uid=user.uid)
            qs = qs.filter(reporter=reporter)
        return qs


class ReporterFilterByLogin(filters.Filter):
    field_class = forms.CharField

    def filter(self, qs, value):
        if value:
            user = blackbox.external_userinfo_by_login(value)
            qs = models.Reporter.objects.filter(uid=user.uid)
        return qs


class RewardFilterSet(filterset.FilterSet):
    login = RewardFilterByLogin(label='Reporter')
    ticket_from = filters.DateFilter(
        name='ticket_created', lookup_expr='gte', label='Ticket created after')
    ticket_till = filters.DateFilter(
        name='ticket_created', lookup_expr='lt', label='Ticket created before')
    payment_from = filters.DateFilter(
        name='payment_created', lookup_expr='gte', label='Payment created after')
    payment_till = filters.DateFilter(
        name='payment_created', lookup_expr='lt', label='Payment created before')

    class Meta:
        model = models.Reward
        fields = [
            'login',
            'status',
            'vulnerability_type',
            'product',
            'protocol',
            'ticket_from',
            'ticket_till',
            'payment_from',
            'payment_till',
        ]


class ReporterFilterSet(filterset.FilterSet):
    login = ReporterFilterByLogin(name='login', label='Reporter')

    class Meta:
        model = models.Reporter
        fields = ['login']
