from django_filters import rest_framework as filters

from verify_trusted.companies.models import Review


class BaseReviewFilter(filters.FilterSet):
    sources = filters.CharFilter(method='sources_filter')
    platforms = filters.CharFilter(method='platforms_filter')
    rating_star = filters.NumberFilter(method='rating_star_filter')

    class Meta:
        model = Review
        fields = []

    def sources_filter(self, queryset, name, value):
        source_ids = value.split(',')
        queryset = queryset.filter(source_id__in=source_ids)
        return queryset

    def platforms_filter(self, queryset, name, value):
        platform_ids = value.split(',')
        queryset = queryset.filter(source__platform_id__in=platform_ids)
        return queryset

    def rating_star_filter(self, queryset, name, value):
        queryset = queryset.filter(rating__gte=int(value), rating__lt=int(value) + 1)
        return queryset


class ReviewFilter(BaseReviewFilter):
    company = filters.NumberFilter(field_name='source__company_id')
    rating_star = filters.CharFilter(method='rating_star_filter')
    sources = filters.CharFilter(method='sources_filter')
    platforms = filters.CharFilter(method='platforms_filter')

    class Meta(BaseReviewFilter.Meta):
        pass

    def rating_star_filter(self, queryset, name, value):
        rating_ids = value.split(',')
        queryset = queryset.filter(rating__in=[int(i) for i in rating_ids])
        return queryset

    def sources_filter(self, queryset, name, value):
        source_ids = value.split(',')
        queryset = queryset.filter(source__platform_id__in=[int(i) for i in source_ids])
        return queryset

    def platforms_filter(self, queryset, name, value):
        platform_ids = value.split(',')
        queryset = queryset.filter(
            source__platform_id__in=[int(i) for i in platform_ids]
        )
        return queryset


class CompanyReviewFilter(BaseReviewFilter):
    rating_star = filters.CharFilter(method='rating_star_filter')

    class Meta(BaseReviewFilter.Meta):
        pass

    def rating_star_filter(self, queryset, name, value):
        rating_ids = value.split(',')
        queryset = queryset.filter(rating__in=[int(i) for i in rating_ids])
        return queryset
