package land.chipmunk.chipmunkmod.util.configurate;

import net.minecraft.util.math.BlockBox;
import net.minecraft.util.math.BlockPos;
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 BlockBoxTypeSerializer implements TypeSerializer<BlockBox> {
    private static final String START = "start";
    private static final String END = "end";

    public static final BlockBoxTypeSerializer INSTANCE = new BlockBoxTypeSerializer();

    private BlockBoxTypeSerializer() {
    }

    @Override
    public BlockBox 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 BlockBox.create(start, end);
    }

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

        target.node(START).set(BlockPos.class, new BlockPos(box.getMinX(), box.getMinY(), box.getMinZ()));
        target.node(END).set(BlockPos.class, new BlockPos(box.getMaxX(), box.getMaxY(), box.getMaxZ()));
    }
}
