# coding: utf-8

from django.db.models import Q

from django.core import mail
from django.http import Http404
from rest_framework import status
from rest_framework.response import Response

from procu.api import models, utils
from procu.api.push.external import notify_enquiry_published
from procu.rest import generics, mixins
from . import permissions, serializers
from ..request.serializers import Request as RequestRetrieve


from procu.api.attachment.serializers import AttachmentEntrySerializer


class RequestPublish(
    generics.CreateMetaMixin, mixins.CreateModelMixin, generics.RetrieveAPIView
):

    serializer_class = serializers.RequestPrepare
    output_serializer_class = RequestRetrieve
    permission_classes = (permissions.PublishRequestPermission,)
    lookup_url_kwarg = 'enquiry_id'

    def get_queryset(self):
        return (
            models.Enquiry.objects.permitted(self.request.user)
            .select_related('draft')
            .prefetch_related('attachments')
        )

    def get_serializer_class(self):

        if self.request.method == 'GET':
            return serializers.RequestPrepare

        return serializers.RequestCreate

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

        try:

            enquiry = self.object

            if enquiry.draft:

                data = enquiry.draft.data

                # Expand attachment ids to objects
                ids = data.pop('attachments', [])
                ids = filter(lambda x: isinstance(x, int) and x > 0, ids)

                # FIXME!!!
                atts = models.Attachment.objects.filter(id__in=ids)

                data['attachments'] = AttachmentEntrySerializer(
                    atts, many=True
                ).data

                return Response(enquiry.draft.data)

            serializer = self.get_serializer(enquiry)
            return Response(serializer.data)

        except Http404:
            return Response({})

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

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        instance = self.perform_create(serializer)

        enquiry = self.object
        enquiry.draft = None
        enquiry.save(update_fields=['draft'])

        # ----------------------------------------------------------------------
        # Notifications

        quotes = models.Quote.objects.values(
            'id', 'supplier_id', 'supplier__title'
        ).filter(request_id=instance.id)

        messages = []

        for quote in quotes:
            messages.extend(notify_enquiry_published(quote['id'], request.user))

        with mail.get_connection(fail_silently=True) as conn:
            conn.send_messages(messages)

        # ----------------------------------------------------------------------
        # Timeline: quotes

        new = [
            {
                'id': q['id'],
                'supplier': {
                    'id': q['supplier_id'],
                    'title': q['supplier__title'],
                },
            }
            for q in quotes
        ]

        models.Log.objects.create(
            enquiry_id=kwargs['enquiry_id'],
            user=request.user,
            type='create_quotes',
            new=utils.json_dumps(new),
        )

        # ----------------------------------------------------------------------
        # Timeline: request

        new = serializers.Log(instance).data

        models.Log.objects.create(
            enquiry_id=kwargs['enquiry_id'],
            user=request.user,
            type='create_request',
            new=utils.json_dumps(new),
        )

        # ----------------------------------------------------------------------

        serializer = self.get_output_serializer(instance)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def perform_create(self, serializer):
        enquiry_id = self.kwargs['enquiry_id']
        return serializer.save(enquiry_id=enquiry_id)
