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


class ChangeRequestTemplateApproversSerializer(
    serializers.ModelSerializer
):
    def to_representation(self, instance):
        try:
            ret = super().to_representation(instance)

            if instance.company:
                
                ret['company'] = {
                    "id": instance.company.id,
                    "code": instance.company.code,
                    "name": instance.company.name
                }
                ret['editable_comp'] = False
            else:
                ret['editable_comp'] = True

            if instance.department:

                ret['department'] = {
                    "id": instance.department.id,
                    "code": instance.department.code,
                    "name": instance.department.name
                }
                ret['editable_dept'] = False
            else:
                ret['editable_dept'] = True

            if instance.user:

                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['user'] = user_object
                ret['editable_user'] = False
            else:
                ret['editable_user'] = True

            if instance.delegation:
                
                ret['delegation'] = {
                    "id": instance.delegation.id,
                    "code": instance.delegation.code,
                    "name": instance.delegation.name
                }
                ret['editable_deleg'] = False
            else:
                ret['editable_deleg'] = True

            if instance.delegation.name.lower() == 'requestor':
                
                ret['editable_user'] = False
                ret['editable_comp'] = False
                ret['editable_dept'] = False
                ret['editable_deleg'] = False

            return ret
        except Exception as e:
            
            ret['editable_user'] = True
            ret['editable_comp'] = True
            ret['editable_dept'] = True
            ret['editable_deleg'] = True
            
            return ret

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