package org.firstinspires.ftc.teamcode;

import com.qualcomm.robotcore.util.ReadWriteFile;

import org.firstinspires.ftc.robotcore.internal.system.AppUtil;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;

public class Replayer extends OpModeWithMovement {
    private final String recordingFileName;
    private JSONObject recordingJSON;
    private int nextIndex = 0;
    private HashMap<GameMotor, API.Motor> motors = new HashMap<>();

    public Replayer(String fileName) {
        this.recordingFileName = fileName;
    }

    @Override
    public void init() {
        this.construct();

        api.print("Status", "Initializing, please wait");
        api.pause(1);

        File recordingFile = AppUtil.getInstance().getSettingsFile(recordingFileName);
        try {
            recordingJSON = new JSONObject(ReadWriteFile.readFile(recordingFile));
        } catch (JSONException e) {
            somethingWentWrong(e);
        }

        for (GameMotor m : GameMotor.values()) {
            motors.put(m, api.new Motor(m.name));
        }

        api.clear();
        api.print("Press play to start");
    }

    @Override
    public void start() {
        api.clear();
        this.resetStartTime();
    }

    @Override
    public void loop() {
        if (nextIndex == -1) return;

        try {
            JSONObject currentListElement = recordingJSON.getJSONArray("recordedData").getJSONObject(nextIndex);
            JSONObject currentData = currentListElement.getJSONObject("data");

            if (this.getRuntime() * 1000 < currentListElement.getDouble("time")) return;

            for (GameMotor m : GameMotor.values()) {
                //noinspection ConstantConditions
                motors.get(m).start(currentData.has(m.name().toLowerCase()) ? currentData.getDouble(m.name().toLowerCase()) : 0);
            }

            nextIndex++;

            if (nextIndex >= recordingJSON.getJSONArray("recordedData").length()) {
                this.requestOpModeStop();
                nextIndex = -1;
            }
        } catch (JSONException e) {
            somethingWentWrong(e);
        }
    }

    public void somethingWentWrong(Exception e) {
        api.print(
            "Why are we here? Just to suffer?" + System.lineSeparator() + e.getMessage()
        );
        this.requestOpModeStop();
        nextIndex = -1;
    }
}
