package land.chipmunk.chipmunkmod.util.configurate;

import com.google.gson.JsonElement;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.serialize.TypeSerializer;

import java.lang.reflect.Type;

public class ComponentTypeSerializer implements TypeSerializer<Component> {
    public static final ComponentTypeSerializer INSTANCE = new ComponentTypeSerializer();
    private static final GsonComponentSerializer GSON = GsonComponentSerializer.gson();

    private ComponentTypeSerializer () {
    }

    @Override
    public Component deserialize (final Type type, final ConfigurationNode source) throws SerializationException {
        final JsonElement elem = source.get(JsonElement.class);
        if (elem == null) {
            return null;
        }

        return GSON.deserializeFromTree(elem);
    }

    @Override
    public void serialize (final Type type, final @Nullable Component component,
                           final ConfigurationNode target) throws SerializationException {
        if (component == null) {
            target.raw(null);
            return;
        }

        final JsonElement elem = GSON.serializeToTree(component);
        target.set(JsonElement.class, elem);
    }
}
