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

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.io.Serial;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

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

    @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 JsonSerializer<?> createContextual(SerializerProvider prov, 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, SerializerProvider provider) throws IOException {
        String text = mapping.get(Objects.toString(value));
        if (text == null || text.isEmpty()) {
            gen.writeObject(value);
        } else {
            gen.writeString(text);
        }
    }
}
