# coding: utf-8

from django.db.models import Prefetch
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter

from procu.api import models
from procu.rest import generics
from procu.rest.filters import IncludeFilter, SearchFilter
from procu.rest.pagination import PageNumberPagination
from procu.rest.permissions import EntryPermission, ListPermission
from .serializers import SupplierTagSerializer


class SupplierTagList(generics.ListCreateAPIView):
    queryset = models.SupplierTag.objects.prefetch_related(
        Prefetch('suppliers', models.Supplier.objects.filter(is_deleted=False))
    )
    serializer_class = SupplierTagSerializer
    pagination_class = PageNumberPagination
    permission_classes = (ListPermission,)
    filter_backends = (
        DjangoFilterBackend,
        IncludeFilter,
        SearchFilter,
        OrderingFilter,
    )
    filter_fields = ('is_hidden',)

    search_fields = ('label', 'comment', 'suppliers__title')

    ordering_fields = ('id', 'label')
    ordering = ('label',)


class SupplierTagEntry(generics.RetrieveUpdateDestroyAPIView):
    queryset = models.SupplierTag.objects.prefetch_related(
        Prefetch('suppliers', models.Supplier.objects.filter(is_deleted=False))
    )
    serializer_class = SupplierTagSerializer
    permission_classes = (EntryPermission,)
    lookup_url_kwarg = 'tag_id'
