package com.njzscloud.common.core.jackson.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonStreamContext;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.njzscloud.common.core.ienum.Dict;
import com.njzscloud.common.core.ienum.DictInt;
import com.njzscloud.common.core.ienum.DictStr;
import com.njzscloud.common.core.ienum.IEnum;

import java.io.IOException;

/**
 * Dict 枚举的 Jackson 序列化器<br/><br/>
 * JSON 格式<br/>
 * 1、枚举不是其他对象的属性<br/>
 * <pre>
 * {
 *   "type": "", // 枚举全限定类名, 反序列化时会用到
 *   "name": "", // name 属性
 *   "ordinal": 0, // ordinal 属性
 *   "val": 1,  // val 属性(字符串/数字), 反序列化时会用到
 *   "txt": "1" // txt 属性
 * }</pre>
 * 2、枚举是其他对象的属性<br/>
 * <pre>
 * {
 *   // ... 其他属性
 *   "原字段名称": 1, // val 属性(字符串/数字), 反序列化时会用到
 *   "原字段名称Txt": "1" //  txt 属性
 * }</pre>
 *
 * @see Dict
 * @see DictInt
 * @see DictStr
 * @see DictDeserializer
 */
public class DictSerializer extends JsonSerializer<Dict> {
    @Override
    public void serialize(Dict value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            gen.writeNull();
        } else {
            JsonStreamContext ctx = gen.getOutputContext();
            if (ctx.inRoot()) {
                gen.writeStartObject();
                gen.writeStringField(IEnum.ENUM_TYPE, value.getClass().getName());
                gen.writeStringField(IEnum.ENUM_NAME, ((Enum<?>) value).name());
                gen.writeNumberField(IEnum.ENUM_ORDINAL, ((Enum<?>) value).ordinal());
                gen.writeObjectField(Dict.ENUM_VAL, value.getVal());
                gen.writeStringField(Dict.ENUM_TXT, value.getTxt());
                gen.writeEndObject();
            } else {
                gen.writeObject(value.getVal());
                String currentName = ctx.getCurrentName();
                gen.writeStringField(currentName + "Txt", value.getTxt());
            }
        }
    }
}
