# coding=utf-8

from rest_framework import serializers

from utils.exceptions import CustomError

from apps.option.models import Option


class OptionSerializer(serializers.ModelSerializer):
    type_name = serializers.CharField(source='get_type_display', read_only=True)
    enable_text = serializers.SerializerMethodField()

    class Meta:
        model = Option
        fields = '__all__'

    def get_enable_text(self, obj):
        if obj.enable:
            return u'是'
        return u'否'

    def create(self, validated_data):
        validated_data['create_user'] = self.context['request'].user
        is_exist = Option.is_exist(validated_data['type'], validated_data['name'])
        if is_exist:
            raise CustomError(u'自定义项[%s]已存在！' % validated_data['name'])
        instance = super(OptionSerializer, self).create(validated_data)
        return instance

    def update(self, instance, validated_data):
        is_exist = Option.is_exist(validated_data['type'], validated_data['name'], instance.id)
        if is_exist:
            raise CustomError(u'自定义项[%s]已存在！' % validated_data['name'])
        instance = super(OptionSerializer, self).update(instance, validated_data)
        return instance
