# coding=utf-8

import django_filters

from django.db.models import Q

from apps.vehicle.models import Brand, Series, Model, VehicleImg


class BrandFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(field_name='name', lookup_expr='icontains')
    enabled = django_filters.CharFilter(field_name='enabled')
    tenant_id = django_filters.CharFilter(field_name='tenant_id')
    id = django_filters.CharFilter(field_name='id')

    class Meta:
        model = Brand
        fields = '__all__'


class SeriesFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(field_name='name', lookup_expr='icontains')
    brand_name = django_filters.CharFilter(field_name='brand__name', lookup_expr='icontains')
    brand_id = django_filters.CharFilter(field_name='brand_id')

    class Meta:
        model = Series
        fields = '__all__'


class ModelFilter(django_filters.FilterSet):
    series_name = django_filters.CharFilter(field_name='series__name', lookup_expr='icontains')
    brand_name = django_filters.CharFilter(field_name='series__brand__name', lookup_expr='icontains')
    series_id = django_filters.CharFilter(method='find_base_series_id')
    search_param = django_filters.CharFilter(method='find_base_search_param')
    is_hot = django_filters.CharFilter(field_name='is_hot')

    def find_base_series_id(self, queryset, *args):
        if args[1] and int(args[1]) > 0:
            queryset = queryset.filter(series_id=args[1])
        return queryset

    def find_base_search_param(self, queryset, *args):
        if args[1]:
            queryset = queryset.filter(
                Q(series__brand__name__icontains=args[1]) |
                Q(series__name__icontains=args[1]) |
                Q(name__icontains=args[1])
            )
        return queryset

    class Meta:
        model = Model
        fields = '__all__'


class VehicleImgFilter(django_filters.FilterSet):

    class Meta:
        model = VehicleImg
        fields = '__all__'

