package com.example.fitbot.util.path;

import com.example.fitbot.exercise.ExerciseManager;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.joml.Vector3f;

public class AnglePath {

    // The angles
    private final Vector3f[] angles;

    /**
     * Create a new gesture path with a given set of vectors and curvature.
     *
     * @param angles The vectors that make up the path.
     */
    public AnglePath(Vector3f[] angles) {
        this.angles = angles;
    }

    /**
     * Method for retrieving the vectors of the GesturePath.
     */
    public Vector3f[] getAngleVectors() {
        return this.angles;
    }

    /**
     * Function for converting a string to a GesturePath object.
     * This function has been updated to convert Json strings to AnglePath objects.
     * The JSON must be in the following format:
     * [
     *  { "deviceId": number, "data": [ [x, y, z], [x, y, z], ... ] },
     * ]
     *
     * @param jsonInput The string to convert
     * @return The AnglePath object
     */

    public static AnglePath[] fromString(String jsonInput) {
        if (jsonInput == null)
            throw new IllegalArgumentException("Input string cannot be null");

        JsonElement parsed = JsonParser.parseString(jsonInput);
        if (!parsed.isJsonArray())
            throw new IllegalArgumentException("Input string must be a JSON array");

        if ( parsed.getAsJsonArray().size() != ExerciseManager.SENSOR_COUNT)
            throw new IllegalArgumentException("Input string must contain 2 elements");

        Vector3f[][] angles = new Vector3f[ExerciseManager.SENSOR_COUNT][];

        for ( int dataArrayIdx = 0; dataArrayIdx < parsed.getAsJsonArray().size(); dataArrayIdx++)
        {
            JsonArray array = parsed.getAsJsonArray().get(dataArrayIdx).getAsJsonObject().get("data").getAsJsonArray();
            int deviceIdx = parsed.getAsJsonArray().get(dataArrayIdx).getAsJsonObject().get("deviceId").getAsInt();
            angles[deviceIdx] = new Vector3f[array.size()];
            for (int i = 0; i < array.size(); i++) {
                JsonArray vec = array.get(i).getAsJsonArray();
                angles[deviceIdx][i] = new Vector3f(vec.get(0).getAsFloat(), vec.get(1).getAsFloat(), vec.get(2).getAsFloat());
            }
        }
        return new AnglePath[] {new AnglePath(angles[0]), new AnglePath(angles[1])};
    }
}
