from rest_framework import serializers
from app.entities import models
from app.applicationlayer.utils import model_to_dict


class ChangeRequestTemplateAttachmentsSerializer(
    serializers.ModelSerializer
):

    def to_representation(self, instance):
        try:
            ret = super().to_representation(instance)
            user_object = {
                "id": instance.uploaded_by.id,
                "name": instance.uploaded_by.name,
                "username": instance.uploaded_by.username,
                "code": instance.uploaded_by.code,
                "email": instance.uploaded_by.email,
                "contact_no": instance.uploaded_by.contact_no
            }
            ret['uploaded_by'] = user_object
            ret['file_upload'] = self.context['request'].build_absolute_uri(
                instance.file_upload.url.url
            )
            ret['file_upload_id'] = instance.file_upload.id
            return ret
        except Exception as e:
            ret['uploaded_by'] = user_object
            return ret

    class Meta:
        model = models.ChangeRequestTemplateAttachments
        # fields = (
        #     "id",
        #     "attachment_type",
        #     "attachment_name",
        #     "file_name",
        #     "description",
        #     "created",
        #     "code",
        #     "uploaded_by",
        #     "file_upload",            
        #     "template_no"
        # )
        fields = '__all__'
        read_only_fields = ['created', 'code']