# coding: utf-8

from rest_framework.response import Response

from procu.api import models
from procu.rest import generics
from procu.rest.pagination import NoPagination
from .permissions import EnquirySummaryPermission
from .serializers import SnapshotSerializer


class SnapshoListCreate(generics.ListCreateAPIView):
    serializer_class = SnapshotSerializer
    pagination_class = NoPagination
    permission_classes = (EnquirySummaryPermission,)

    def get_queryset(self):
        return models.QuoteProductSnapshot.objects.filter(
            enquiry=self.enquiry
        ).order_by('pk')

    def post_initial(self, request):
        enquiry = self.enquiry = generics.get_object_or_404(
            models.Enquiry.objects.permitted(self.request.user),
            pk=self.kwargs['enquiry_id'],
        )
        self.check_object_permissions(request, enquiry)

    def check_object_permissions(self, request, enquiry):
        super().check_object_permissions(request, enquiry)

        if request.method == 'POST':
            has_products = (
                models.QuoteProduct.objects.filter(
                    quote__request__enquiry=self.enquiry
                )
            ).exists()

            if not has_products:
                self.permission_denied(request)

    def post(self, request, *args, **kwargs):

        products = list(
            models.QuoteProduct.objects.values().filter(
                quote__request__enquiry=self.enquiry
            )
        )

        snapshot = models.QuoteProductSnapshot.objects.create(
            enquiry=self.enquiry
        )

        for qp in products:
            qp['snapshot_id'] = snapshot.id
            qp['parent_id'] = qp['id']
            qp.pop('id')
            models.QuoteProduct.objects.create(**qp)

        return Response({'results': 'OK'})
