import django_filters

from rest_framework.filters import BaseFilterBackend

from companies.models import Company
from products.models import Product


class CompanyTagFilter(django_filters.FilterSet):

    tags = django_filters.CharFilter(method='tag_filter')

    class Meta:
        model = Company
        fields = ['tags', 'city',]

    def tag_filter(self, queryset, name, value):
        return queryset.filter(**{
            name: value,
        })


class ProductTagFilter(django_filters.FilterSet):

    tags = django_filters.CharFilter(method='tag_filter')
    attributes = django_filters.CharFilter(method='tag_filter')
    category = django_filters.CharFilter(method='tag_filter')

    class Meta:
        model = Product
        fields = ['name', 'tags', 'category', 'attributes', 'company', 'created',]

    def tag_filter(self, queryset, name, value):
        return queryset.filter(**{
            name: value,
        })


class ProductOrderFilter(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        order_field = request.GET.get('order', None)
        if order_field is not None:
            return queryset.order_by(order_field)
        else:
            return queryset

