# coding: utf-8
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter

from procu.api import models
from procu.api.enquiry.filters import StatusFilter
from procu.rest import generics, pagination, permissions
from . import filters, serializers
from .permissions import UpdateQuotePermission


class RequestList(generics.ListAPIView):
    serializer_class = serializers.List
    pagination_class = pagination.PageNumberPagination
    permission_classes = (permissions.ExternalOnly,)

    filter_backends = (
        filters.RequestOrderingFilter,
        DjangoFilterBackend,
        StatusFilter,
        SearchFilter,
    )

    ordering_fields = (
        'id',
        'status',
        'deadline_at',
        'has_offer',
        'has_won',
        'updated_at',
        'request__key',
        'request__enquiry_id',
        'request__subject',
    )
    ordering = ('-updated_at',)
    filter_fields = ('has_offer',)
    search_fields = ('request__key', 'request__subject', 'request__description')

    def get_queryset(self):
        return (
            models.Quote.objects.permitted(self.request.user)
            .filter(request__isnull=False)
            .select_related('request')
        )


class RequestRetrieveUpdate(generics.RetrieveUpdateAPIView):
    permission_classes = (permissions.ExternalOnly, UpdateQuotePermission)
    lookup_url_kwarg = 'quote_id'

    def get_serializer_class(self):
        if self.request.method == 'PATCH':
            return serializers.Update
        else:
            return serializers.Retrieve

    def get_queryset(self):
        return (
            models.Quote.objects.permitted(self.request.user)
            .select_related('request')
            .filter(request__isnull=False)
        )
