package land.chipmunk.chipmunkmod.util.configurate;

import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.renderer.ComponentRenderer;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.gson.GsonConfigurationLoader;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.serialize.TypeSerializerCollection;
import org.spongepowered.configurate.transformation.TransformAction;

import java.util.Arrays;

public final class ConfigurateUtilities {
    private static final TypeSerializerCollection CUSTOM_SERIALIZER_COLLECTION = TypeSerializerCollection.builder()
            .registerAll(GsonConfigurationLoader.gsonSerializers())
            .register(BlockPos.class, BlockPosTypeSerializer.INSTANCE)
            .register(BoundingBox.class, BlockBoxTypeSerializer.INSTANCE)
            .register(Component.class, ComponentTypeSerializer.INSTANCE)
            .build();

    private ConfigurateUtilities () {
    }

    public static TypeSerializerCollection customSerializers () {
        return CUSTOM_SERIALIZER_COLLECTION;
    }

    public static ConfigurationNode getNodeOrThrow (final ConfigurationNode source, final Object... path) throws SerializationException {
        if (!source.hasChild(path)) {
            throw new SerializationException("Required field " + Arrays.toString(path) + " was not present in node");
        }

        return source.node(path);
    }

    public static <C> TransformAction componentTransformer (final ComponentRenderer<C> renderer, final C ctx) {
        return (path, value) -> {
            final Component originalComponent = value.get(Component.class);
            if (originalComponent == null) return null;

            final Component newComponent = renderer.render(originalComponent, ctx);
            value.set(Component.class, newComponent);
            return null;
        };
    }
}
