package com.tofly.base.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.tofly.base.anno.DisplayText;
import com.tofly.base.converter.Converter;

import java.io.IOException;

/**
 *
 */
public class DisplayTextSerializer extends JsonSerializer<Object> implements ContextualSerializer {

    private Class<?> cls;
    private String fieldName;

    public DisplayTextSerializer() {}

    public DisplayTextSerializer(Class<?> cls, String fieldName) {
        this.cls = cls;
        this.fieldName = fieldName;
    }

    @Override
    public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeObject(value);
        if (value == null) {
            return;
        }
        if (!Converter.class.isAssignableFrom(cls)) {
            return;
        }
        Converter converter = (Converter) ApplicationContextHolder.INSTANCE.getBean(cls);
        jsonGenerator.writeStringField(fieldName, converter.convert(value));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty == null) {
            return serializerProvider.findNullValueSerializer(null);
        }
        DisplayText displayText = beanProperty.getAnnotation(DisplayText.class);
        if (displayText == null || !ConvertGroupHolder.ifConvert(displayText.group())) {
            return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }
        return new DisplayTextSerializer(displayText.converter(), beanProperty.getName() + displayText.suffix());
    }
}
