# coding: utf-8

from procu.api import models
from procu.api.utils import dict_diff, is_readonly, json_dumps
from procu.rest import generics
from . import permissions, serializers
from .utils import create_enquiry_comment


class CommentListCreate(generics.ListCreateAPIView):
    permission_classes = (permissions.ListCreate,)
    output_serializer_class = serializers.RetrieveUpdate

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

    def get_queryset(self):
        queryset = (
            models.EnquiryComment.objects.filter(
                enquiry=self.kwargs['enquiry_id']
            )
            .select_related('author')
            .prefetch_related('invitees', 'attachments')
            .order_by('-id')
        )

        if is_readonly():
            queryset = queryset.extra(select={'can_edit': 'false'})
        else:
            queryset = queryset.extra(
                select={'can_edit': 'author_id = %s'},
                select_params=(self.request.user.id,),
            )

        return queryset

    def perform_create(self, serializer):
        data = serializer.validated_data
        return create_enquiry_comment(
            enquiry_id=self.kwargs['enquiry_id'],
            user=self.request.user,
            data={'message': data['message']},
            invitees=data['invitees'],
            attachment_ids=[x.id for x in data['attachments']],
            notify=True,
        )


class CommentRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = (permissions.UpdateDelete,)
    lookup_url_kwarg = 'comment_id'
    serializer_class = serializers.RetrieveUpdate

    def get_queryset(self):
        return models.EnquiryComment.objects.permitted(
            self.request.user
        ).filter(enquiry=self.kwargs['enquiry_id'])

    def perform_update(self, serializer):
        old = serializers.Log(serializer.instance).data
        instance = serializer.save()

        new = serializers.Log(instance).data
        diff = dict_diff(old, new)

        if diff:
            models.Log.objects.create(
                quote=None,
                enquiry_id=self.kwargs['enquiry_id'],
                user=self.request.user,
                type='update_enquiry_comment',
                data=json_dumps(diff),
                old=json_dumps(old),
                new=json_dumps(serializer.data),
            )

    def perform_destroy(self, instance):
        old = serializers.Log(instance).data
        super().perform_destroy(instance)

        models.Log.objects.create(
            enquiry_id=self.kwargs['enquiry_id'],
            user=self.request.user,
            type='remove_enquiry_comment',
            data=json_dumps(old),
            old=json_dumps(old),
        )
