# coding=utf-8

from rest_framework import generics

from utils import response_ok
from utils.exceptions import CustomError
from .serializers import SeriesSerializer, ModelSerializer, ModelDetailSerializer
from apps.vehicle.filters import SeriesFilter, ModelFilter
from apps.vehicle.models import Series, Model
from utils.permission import IsCustomerUser


class SeriesListViewSet(generics.ListAPIView):
    # permission_classes = [IsCustomerUser, ]
    queryset = Series.objects.filter(enabled=True, delete=False)
    serializer_class = SeriesSerializer

    def filter_queryset(self, queryset):
        f = SeriesFilter(self.request.GET, queryset=queryset)
        return f.qs

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return response_ok(serializer.data)


class ModelListViewSet(generics.ListAPIView):
    # permission_classes = [IsCustomerUser, ]
    queryset = Model.objects.filter(enabled=True, delete=False)
    serializer_class = ModelSerializer

    def filter_queryset(self, queryset):
        f = ModelFilter(self.request.GET, queryset=queryset)
        return f.qs

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return response_ok(serializer.data)


class ModelDetailViewSet(generics.RetrieveAPIView):
    # permission_classes = [IsCustomerUser, ]
    queryset = Model.objects.filter(enabled=True, delete=False)
    serializer_class = ModelDetailSerializer

    def retrieve(self, request, *args, **kwargs):
        id = request.GET.get('id')
        instance = self.queryset.filter(id=id).first()
        if not instance:
            raise CustomError(u'未找到相应的车辆！')
        serializer = self.get_serializer(instance)
        return response_ok(serializer.data)

