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


class ChangeRequestFormStakeHoldersSerializer(
    serializers.ModelSerializer
):
    def to_representation(self, instance):
        try:
            ret = super().to_representation(instance)
            user_object = {
                "id": instance.user.id,
                "name": instance.user.name,
                "username": instance.user.username,
                "code": instance.user.code,
                "email": instance.user.email,
                "contact_no": instance.user.contact_no
            }
            ret['company'] = model_to_dict(instance.user.department.company)
            ret['department'] = model_to_dict(instance.user.department)
            ret['user'] = user_object

            return ret
        except Exception as e:
            ret['company'] = "none"
            ret['department'] = "none"
            ret['name'] = "none"
            return ret

    class Meta:
        model = models.ChangeRequestFormStakeHolders
        fields = '__all__'
        read_only_fields = ['created', 'code']