package tech.nevets.jaml.util;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.apache.commons.io.FileUtils;
import tech.nevets.jaml.JAML;
import tech.nevets.jaml.objects.Loader;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class LoaderUtils {

    public static String[] getLoaders() {
        try {
            Gson gson = new Gson();
            File loadersFile = getLoadersList();
            JsonObject loadersJson = gson.fromJson(FileUtils.readFileToString(loadersFile, StandardCharsets.UTF_8), JsonObject.class);
            JsonArray loadersJsonArray = loadersJson.getAsJsonArray("loaders");
            Loader[] loadersArray = gson.fromJson(loadersJsonArray, Loader[].class);
            String[] loadersArrayList = new String[loadersArray.length];

            for (int i = 0; i < loadersArrayList.length; i++) {
                loadersArrayList[i] = loadersArray[i].getId();
            }

            return loadersArrayList;

        } catch (IOException e) {
            e.printStackTrace();
            return new String[]{"Vanilla", "Fabric", "Forge"}; // Fallback variable
        }
    }

    private static File getLoadersList() {
        File loadersFile;
        try {
            loadersFile = new File(JAML.path + "\\data\\loaders.json");
            FileUtils.copyURLToFile(new URL("https://api.nevets.tech/jaml/loaders.json"), loadersFile);
        } catch (IOException e) {
            e.printStackTrace();
            loadersFile = new File("");
        }
        return loadersFile;
    }
}
