# coding: utf-8

from django.core import mail

from procu.api import models
from procu.api.common.products import (
    OfferSnapshot,
    update_products,
    validate_products,
)
from procu.api.push.internal import notify_quote_products
from procu.api.utils import json_dumps
from procu.rest import generics, permissions
from . import serializers
from .permissions import ListReplaceProductsPermission


class ProductReplace(generics.ListReplaceAPIView):
    permission_classes = (
        permissions.ExternalOnly,
        ListReplaceProductsPermission,
    )
    serializer_class = serializers.QuoteProduct

    def get_queryset(self):
        return models.QuoteProduct.objects.filter(quote=self.kwargs['quote_id'])

    def perform_replace(self, serializer):

        quote_id = self.kwargs['quote_id']
        products = serializer.validated_data

        old = OfferSnapshot.create(quote_id)

        validate_products(quote_id, products)
        update_products(quote_id, products)

        # ----------------------------------------------------------------------
        # Timeline

        new = OfferSnapshot.create(quote_id)
        diff = old.diff(new)

        if diff:
            enquiry_id = models.Request.objects.values_list(
                'enquiry_id', flat=True
            ).get(quotes=quote_id)

            models.Log.objects.create(
                enquiry_id=enquiry_id,
                quote_id=quote_id,
                user=self.request.user,
                type='replace_quote_products_diff',
                data=json_dumps(diff),
            )

        # ----------------------------------------------------------------------
        # Notification

        messages = notify_quote_products(quote_id, self.request.user)
        with mail.get_connection(fail_silently=True) as conn:
            conn.send_messages(messages)
