# coding=utf-8

from rest_framework import serializers
from .models import Subject, Chapter
from utils.exceptions import CustomError


class SubjectSerializer(serializers.ModelSerializer):

    class Meta:
        model = Subject
        fields = "__all__"

    def create(self, validated_data):
        instance = super(SubjectSerializer, self).create(validated_data)
        return instance

    def update(self, instance, validated_data):
        instance = super(SubjectSerializer, self).update(instance, validated_data)
        return instance


class ChapterSerializer(serializers.ModelSerializer):
    subject_name = serializers.CharField(source='subject.name', read_only=True)

    class Meta:
        model = Chapter
        fields = "__all__"

    def validate(self, attrs):
        if 'subject' in attrs and attrs['subject'].delete:
            raise CustomError(u'科目[%s]已被删除！' % attrs['subject'].name)
        return attrs

    def create(self, validated_data):
        instance = super(ChapterSerializer, self).create(validated_data)
        return instance

    def update(self, instance, validated_data):
        instance = super(ChapterSerializer, self).update(instance, validated_data)
        return instance


class SubjectSimpleSerializer(serializers.ModelSerializer):

    class Meta:
        model = Subject
        fields = ['id', 'name', ]


class ChapterSimpleSerializer(serializers.ModelSerializer):

    class Meta:
        model = Chapter
        fields = ['id', 'name', 'subject_id' ]
