package eu.mhsl.craftattack.teamLobby.util;

import com.google.gson.*;
import net.minestom.server.coordinate.Pos;

import java.lang.reflect.Type;

public class PosSerializer {
    private static final Gson gson = new GsonBuilder()
        .registerTypeAdapter(Pos.class, new PosAdapter())
        .create();

    public static String serialize(Pos pos) {
        return gson.toJson(pos);
    }

    public static Pos deserialize(String json) {
        return gson.fromJson(json, Pos.class);
    }

    private static class PosAdapter implements JsonSerializer<Pos>, JsonDeserializer<Pos> {

        @Override
        public JsonElement serialize(Pos src, Type typeOfSrc, JsonSerializationContext context) {
            JsonObject obj = new JsonObject();
            obj.addProperty("x", src.x());
            obj.addProperty("y", src.y());
            obj.addProperty("z", src.z());
            obj.addProperty("yaw", src.yaw());
            obj.addProperty("pitch", src.pitch());
            return obj;
        }

        @Override
        public Pos deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            JsonObject obj = json.getAsJsonObject();
            double x = obj.get("x").getAsDouble();
            double y = obj.get("y").getAsDouble();
            double z = obj.get("z").getAsDouble();
            float yaw = obj.has("yaw") ? obj.get("yaw").getAsFloat() : 0f;
            float pitch = obj.has("pitch") ? obj.get("pitch").getAsFloat() : 0f;
            return new Pos(x, y, z, yaw, pitch);
        }
    }

}
