from django_filters import (
    CharFilter,
    FilterSet,
    IsoDateTimeFromToRangeFilter,
    NumberFilter,
)

from verify_trusted.companies.history_types import HistoryType, HistoryTypeSymbol
from verify_trusted.companies.models import Company


class ReviewSourceChangelogFilter(FilterSet):
    platform = NumberFilter(field_name='platform__id')
    company = NumberFilter(
        field_name='company__id',
    )
    company_name = CharFilter(method='name_filter')
    type = CharFilter(method='type_filter')
    date = IsoDateTimeFromToRangeFilter(field_name='history_date')

    def name_filter(self, queryset, name, value):
        company_ids = Company.objects.filter(search_vector=value).values_list(
            'id', flat=True
        )
        queryset = queryset.filter(company_id__in=company_ids)
        return queryset

    def type_filter(self, queryset, name, value):
        if value == HistoryType.CREATED:
            queryset = queryset.filter(history_type=HistoryTypeSymbol.CREATED)
        if value == HistoryType.CHANGED:
            queryset = queryset.filter(history_type=HistoryTypeSymbol.CHANGED)
        if value == HistoryType.DELETED:
            queryset = queryset.filter(history_type=HistoryTypeSymbol.DELETED)
        return queryset
