import json

from rest_framework import serializers

from books.schema.mutations.utils import handle_content_block
from rooms.models import Room, RoomEntry


class ContentsSerializer(serializers.Field):
    def to_internal_value(self, data):
        return json.dumps(list(map(handle_content_block, data)))


class RoomSerializer(serializers.ModelSerializer):
    class Meta:
        model = Room
        fields = ('id', 'title', 'description', 'slug', 'school_class', 'appearance',)
        read_only_fields = ('id', 'slug',)


class RoomEntrySerializer(serializers.ModelSerializer):
    contents = ContentsSerializer()

    class Meta:
        model = RoomEntry
        fields = ('room', 'author', 'title', 'contents')
        read_only_fields = ('id', 'slug',)

    def validate_contents(self, value):
        return value

    def create(self, validated_data):
        room_entry = RoomEntry(**validated_data)
        room_entry.save()
        return room_entry
