# coding: utf-8

from procu.api import models
from procu.api.enquiry.invoice import serializers
from procu.api.enquiry.invoice.timeline import InvoiceSnapshot
from procu.api.enums import ES
from procu.api.utils import is_readonly, json_dumps
from procu.rest import generics
from .permissions import InvoiceProductUpdatePermission


class InvoiceProductRetrieveUpdate(generics.RetrieveUpdateAPIView):
    permission_classes = (InvoiceProductUpdatePermission,)
    lookup_url_kwarg = 'invoiceproduct_id'

    def get_serializer_class(self):
        if self.request.method == 'PATCH':
            if self.request.user.is_staff:
                return serializers.InvoiceProductUpdateInternal
            else:
                return serializers.InvoiceProductUpdateExternal
        return serializers.InvoiceProductRaw

    def get_serializer_context(self):
        user = self.request.user
        enquiry = self.invoice.enquiry

        context = super().get_serializer_context()

        if user.is_staff:
            summary_perm = 'api.summary_enquiry'
            can_see_prices = summary_perm in enquiry.permissions(user)
        else:
            can_see_prices = True

        context['can_see_prices'] = can_see_prices

        context['can_update'] = (
            not is_readonly()
            and (user.is_staff or enquiry.status < ES.CLOSED)
            and user.has_perm('api.update_invoiceproduct')
        )

        return context

    def perform_update(self, serializer):
        old = InvoiceSnapshot.create(self.kwargs['invoice_id'])
        super().perform_update(serializer)

        new = InvoiceSnapshot.create(self.kwargs['invoice_id'])
        diff = old.diff_update(new)
        if diff:
            models.Log.objects.create(
                enquiry_id=self.invoice.enquiry_id,
                user=self.request.user,
                type='update_invoice',
                data=json_dumps(diff),
            )

    def get_queryset(self):
        invoice = self.invoice = generics.get_object_or_404(
            models.Invoice.objects.permitted(self.request.user).select_related(
                'enquiry'
            ),
            id=self.kwargs['invoice_id'],
        )

        return invoice.products.select_related('currency', 'unit', 'invoice')
