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;

public class BlockPosTypeSerializer implements TypeSerializer<BlockPos> {
    public static final BlockPosTypeSerializer INSTANCE = new BlockPosTypeSerializer();
    private static final String X = "x";
    private static final String Y = "y";
    private static final String Z = "z";

    private BlockPosTypeSerializer () {
    }

    @Override
    public BlockPos deserialize (final Type type, final ConfigurationNode source) throws SerializationException {
        final int x = ConfigurateUtilities.getNodeOrThrow(source, X).getInt();
        final int y = ConfigurateUtilities.getNodeOrThrow(source, Y).getInt();
        final int z = ConfigurateUtilities.getNodeOrThrow(source, Z).getInt();

        return new BlockPos(x, y, z);
    }

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

        target.node(X).set(pos.getX());
        target.node(Y).set(pos.getY());
        target.node(Z).set(pos.getZ());
    }
}
