# Generated by uml2django
# https://github.com/J-hanks/uml2django

from django.utils.text import slugify

from rest_framework import serializers

from educational.models import Subject
from educational.models.SubjectLevel import SubjectLevel
from educational.models.SubjectRequirement import SubjectRequirement

from educational.rest_api.serializers.SubjectLevelSerializer import SubjectLevelSerializer
from educational.rest_api.serializers.SubjectRequirementSerializer import SubjectRequirementSerializer


class SubjectSerializer(serializers.ModelSerializer):
    subjectlevel_set = SubjectLevelSerializer(
        # source='subjectlevel_set',
        many=True,
        required=False, 
        allow_null=True
    )
    subjectrequirement_set = SubjectRequirementSerializer(
        # source='subjectrequirement_set',
        many=True,
        required=False, 
        allow_null=True
    )
    

    class Meta:
        model = Subject
        fields = [
            'title',
            'name',
            'slug',
            'subjectlevel_set',
            'subjectrequirement_set',
        ]
        read_only_fields = ['slug']
        lookup_field = 'slug'
        extra_kwargs = {
            'url': {'lookup_field': 'slug'}
        }

    def create(self, validated_data):
        subjectlevel_set_data = validated_data.pop('subjectlevel_set')
        subjectrequirement_set_data = validated_data.pop('subjectrequirement_set')
        subject = Subject(**validated_data)
        for subjectlevel_data in subjectlevel_set_data:
            SubjectLevel.objects.create(
                subject=subject,
                **subjectlevel_data
            )
        for subjectrequirement_data in subjectrequirement_set_data:
            SubjectRequirement.objects.create(
                subject=subject,
                **subjectrequirement_data
            )

        subject.slug = slugify(subject.name)
        subject.save()
        return subject
