# coding: utf-8

from django.utils.timezone import now

from procu.api import models
from procu.api.utils import is_readonly
from procu.rest import generics
from procu.rest.permissions import EntryPermission, ListPermission
from . import serializers


class WarningListCreate(generics.ListCreateAPIView):
    permission_classes = (ListPermission,)
    queryset = models.SupplierWarning.objects.all()

    def get_serializer_class(self):
        if self.request.method == 'POST':
            return serializers.Create
        else:
            return serializers.List

    def get_queryset(self):
        return (
            models.SupplierWarning.objects.select_related('author')
            .filter(supplier=self.kwargs['supplier_id'], is_deleted=False)
            .order_by('-id')
        )

    def get_serializer_context(self):
        context = super().get_serializer_context()
        context['is_readonly'] = is_readonly()
        return context

    def post_initial(self, request):
        self.supplier = generics.get_object_or_404(
            models.Supplier.objects.only('id'), pk=self.kwargs['supplier_id']
        )

    def perform_create(self, serializer):
        return serializer.save(author=self.request.user, supplier=self.supplier)


class WarningRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = (EntryPermission,)
    serializer_class = serializers.RetrieveUpdate

    lookup_url_kwarg = 'warning_id'

    def get_queryset(self):
        return models.SupplierWarning.objects.select_related('author').filter(
            supplier=self.kwargs['supplier_id'], is_deleted=False
        )

    def perform_update(self, serializer):
        return serializer.save(updated_at=now())
