from rest_framework import serializers
from app.entities.models import Module, Application
# from app.applicationlayer.management.application import ApplicationSerializer


class SubModuleField(serializers.Field):

    def to_representation(self, value):

        list_sub_module = Module.objects.filter(
            parent=value.id
        ).values().order_by('sort_id')

        return list_sub_module


class ModuleSerializer(serializers.ModelSerializer):
    sub_module = SubModuleField(source='*', read_only=True)
    
    def to_representation(self, instance):
        application_name = Application.objects.filter(
            id=instance.application.id
        ).values().first()
        ret = super().to_representation(instance)
        ret['application'] = application_name

        return ret

    class Meta:
        model = Module
        fields = '__all__'
        read_only_fields = (
            'created', 'createdby', 'modified', 'modifiedby', 'code',
        )
