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 ChangelogFilter(FilterSet):
    company_id = NumberFilter(field_name='id')
    name = CharFilter(method='name_filter')
    type = CharFilter(method='type_filter')
    user_id = NumberFilter(field_name='history_user_id')
    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(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.exclude(
                history_change_reason=HistoryType.CLAIMED
            ).filter(history_type=HistoryTypeSymbol.CHANGED)
        if value == HistoryType.CLAIMED:
            queryset = queryset.filter(history_change_reason=HistoryType.CLAIMED)
        return queryset


class ReviewChangelogFilter(FilterSet):
    company = NumberFilter(field_name='source__company_id')
    author = CharFilter(field_name='author')
    type = CharFilter(method='type_filter')
    date = IsoDateTimeFromToRangeFilter(field_name='history_date')

    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
