/* (C) 2021 YiRing, Inc. */
package com.yiring.common.jackson;

import java.io.Serial;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import tools.jackson.core.JacksonException;
import tools.jackson.core.JsonGenerator;
import tools.jackson.databind.BeanProperty;
import tools.jackson.databind.SerializationContext;
import tools.jackson.databind.ValueSerializer;
import tools.jackson.databind.ser.std.StdSerializer;

/**
 * Mapping 序列化
 *
 * @author Jim
 * @version 0.1
 * 2021/10/15 18:11
 */
public class ObjectMappingSerializer extends StdSerializer<Object> implements Serializable {

    @Serial
    private static final long serialVersionUID = -1924851196524453827L;

    protected ObjectMappingSerializer() {
        super(Object.class);
    }

    private final Map<String, String> mapping = new HashMap<>();

    public void putAll(Map<String, String> map) {
        this.mapping.putAll(map);
    }

    @Override
    public ValueSerializer<?> createContextual(SerializationContext ctx, BeanProperty property) {
        MappingSerialize mappingSerialize = property.getAnnotation(MappingSerialize.class);
        String mapping = mappingSerialize.mapping();

        Map<String, String> map = new HashMap<>();
        if (!mapping.isEmpty()) {
            String[] strings = mapping.split(",");
            for (String str : strings) {
                String[] split = str.split(":");
                map.put(split[0], split[1]);
            }
        }

        ObjectMappingSerializer serializer = new ObjectMappingSerializer();
        serializer.putAll(map);
        return serializer;
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializationContext provider) throws JacksonException {
        String text = mapping.get(Objects.toString(value));
        if (text == null || text.isEmpty()) {
            gen.writeObjectRef(value);
        } else {
            gen.writeString(text);
        }
    }
}
