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

from django.utils.text import slugify

from rest_framework import serializers

from infrastructure.models import ClassRoom
from infrastructure.models.WorkingPeriod import WorkingPeriod

from infrastructure.rest_api.serializers.WorkingPeriodSerializer import WorkingPeriodSerializer


class ClassRoomSerializer(serializers.ModelSerializer):
    workingperiod_set = WorkingPeriodSerializer(
        # source='workingperiod_set',
        many=True,
        required=False, 
        allow_null=True
    )
    

    class Meta:
        model = ClassRoom
        fields = [
            'building',
            'name',
            'slug',
            'workingperiod_set',
        ]
        read_only_fields = ['slug']
        lookup_field = 'slug'
        extra_kwargs = {
            'url': {'lookup_field': 'slug'}
        }

    def create(self, validated_data):
        workingperiod_set_data = validated_data.pop('workingperiod_set')
        classroom = ClassRoom(**validated_data)
        for workingperiod_data in workingperiod_set_data:
            WorkingPeriod.objects.create(
                classroom=classroom,
                **workingperiod_data
            )

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