# coding=utf-8

import django_filters

from .models import UsedVehicle, UsedVehicleImg


class UsedVehicleFilter(django_filters.FilterSet):
    brand = django_filters.CharFilter(field_name='brand')
    number = django_filters.CharFilter(field_name='number', lookup_expr='icontains')
    status = django_filters.CharFilter(field_name='status')
    gearbox = django_filters.CharFilter(field_name='gearbox')
    color = django_filters.CharFilter(field_name='color')
    displacement = django_filters.CharFilter(field_name='displacement')
    emission = django_filters.CharFilter(field_name='emission')
    seat_count = django_filters.CharFilter(field_name='seat_count')
    oil_type = django_filters.CharFilter(field_name='oil_type')

    price_range = django_filters.CharFilter(method='find_base_range_price')
    mileage_range = django_filters.CharFilter(method='find_base_range_mileage')
    years_range = django_filters.CharFilter(method='find_base_range_years')

    def find_base_range_price(self, queryset, *args):
        if args[1]:
            prices = args[1].split(',')
            b_price = int(prices[0]) * 10000
            if len(prices) > 1:
                e_price = int(prices[1]) * 10000
                queryset = queryset.filter(sale_price__gte=b_price, sale_price__lte=e_price)
            else:
                queryset = queryset.filter(sale_price__gte=b_price)
        return queryset

    def find_base_range_mileage(self, queryset, *args):
        if args[1]:
            mileages = args[1].split(',')
            b_mileage = int(mileages[0]) * 10000
            if len(mileages) > 1:
                e_mileage = int(mileages[1]) * 10000
                queryset = queryset.filter(mileage__gte=b_mileage, mileage__lte=e_mileage)
            else:
                queryset = queryset.filter(mileage__gte=b_mileage)
        return queryset

    def find_base_range_years(self, queryset, *args):
        if args[1]:
            years = args[1].split(',')
            b_year = int(years[0])
            if len(years) > 1:
                e_year = int(years[1])
                queryset = queryset.filter(years__gte=b_year, years__lte=e_year)
            else:
                queryset = queryset.filter(years__gte=b_year)
        return queryset

    class Meta:
        model = UsedVehicle
        fields = '__all__'

class UsedVehicleImgFilter(django_filters.FilterSet):
    main = django_filters.CharFilter(field_name='main')

    class Meta:
        model = UsedVehicleImg
        fields = '__all__'
