import copy
from rest_framework import status, viewsets
from rest_framework.response import Response
from app.entities.models import MasterAttachment
from app.applicationlayer.master.attachment.serializer import MasterAttachmentSerializer
from app.applicationlayer.utils import CustomPagination, status_message_response
from django.db import transaction
from rest_framework.exceptions import ValidationError


class MasterAttachmentViewSet(viewsets.ModelViewSet):
    queryset = MasterAttachment.objects.all()
    serializer_class = MasterAttachmentSerializer
    pagination_class = CustomPagination
    # @decorators.rms.user_list
    def list(self, request, *args, **kwargs):

        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)

        if page is not None:
            serializer = self.get_serializer(page, many=True)

            message = status_message_response(
                200,
                'success',
                'list of Attachment found',
                serializer.data
            )

            return self.get_paginated_response(message)

        serializer = self.get_serializer(queryset, many=True)

        return Response(
            serializer.data,
            status=status.HTTP_200_OK
        )

    @transaction.atomic
    def create(self, request, *args, **kwargs):
        attachments = []
        for key in request.data.keys():
            for instance in self.request.data.getlist(key):

                body = {}
                data = MasterAttachment.objects.create(
                    url=instance,
                    attch_ref=key
                )

                file_name = str(data.url).split('/')
                body['id'] = data.id
                body['file_name'] = instance.name
                body['attch_ref'] = key
                attachments.append(body)

        return Response(
            {"results": attachments},
            status=status.HTTP_201_CREATED
        )
