package land.chipmunk.chipmunkmod.util.configurate;

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;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.levelgen.structure.BoundingBox;

public class BlockBoxTypeSerializer implements TypeSerializer<BoundingBox> {
    public static final BlockBoxTypeSerializer INSTANCE = new BlockBoxTypeSerializer();
    private static final String START = "start";
    private static final String END = "end";

    private BlockBoxTypeSerializer () {
    }

    @Override
    public BoundingBox deserialize (final Type type, final ConfigurationNode source) throws SerializationException {
        final BlockPos start = ConfigurateUtilities.getNodeOrThrow(source, START).require(BlockPos.class);
        final BlockPos end = ConfigurateUtilities.getNodeOrThrow(source, END).require(BlockPos.class);

        return BoundingBox.fromCorners(start, end);
    }

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

        target.node(START).set(BlockPos.class, new BlockPos(box.minX(), box.minY(), box.minZ()));
        target.node(END).set(BlockPos.class, new BlockPos(box.maxX(), box.maxY(), box.maxZ()));
    }
}
