# coding=utf-8

from rest_framework import generics
from rest_framework.exceptions import NotFound
from utils.permission import IsCustomerUser

from utils import response_ok
from utils.exceptions import CustomError

from apps.product.models import Product
from apps.product.filters import ProductFilter
from apps.foundation.models import  Option
from apps.foundation.filters import OptionFilter

from .serializers import ProductSerializer, ProductDetailSerializer, ProductTypeSerializer


class ProductListView(generics.ListAPIView):
    # permission_classes = [IsCustomerUser, ]
    queryset = Product.objects.filter(delete=False, enabled=True)
    serializer_class = ProductSerializer

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

    def list(self, request, *args, **kwargs):
        try:
            data = super(ProductListView, self).list(request)
        except NotFound:
            return response_ok([])
        return data


class ProductTypeListView(generics.ListAPIView):
    # permission_classes = [IsCustomerUser, ]
    queryset = Option.objects.filter(enable=True, delete=False, type=Option.PRODUCT_CATEGORY)
    serializer_class = ProductTypeSerializer

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

    def list(self, request, *args, **kwargs):
        try:
            data = super(ProductTypeListView, self).list(request)
        except NotFound:
            return response_ok([])
        return data


class ProductDetailView(generics.RetrieveAPIView):
    # permission_classes = [IsCustomerUser, ]
    queryset = Product.objects.filter(enabled=True, delete=False)
    serializer_class = ProductDetailSerializer

    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)
