package tech.nevets.jaml.util;

import com.google.gson.*;
import org.apache.commons.io.FilenameUtils;
import tech.nevets.jaml.Config;
import tech.nevets.jaml.JAML;
import tech.nevets.jaml.objects.Profile;

import java.io.*;
import java.nio.file.Path;

public class ProfileUtils {
    private static final Path PROFILE_PATH = Path.of(JAML.path + "\\profiles\\");
    public static Profile activeProfile;
    public static String[] profileList;

    public static void createProfile(Profile profile) throws IOException {
        String profileName = profile.getProfileName();
        Writer writer = new FileWriter(PROFILE_PATH + "\\" + profileName + ".json");

        GsonBuilder builder = new GsonBuilder();
        builder.setPrettyPrinting();
        Gson gson = builder.create();
        String jsonString = gson.toJson(profile);
        writer.write(jsonString);
        writer.close();

        loadProfile(profileName);
    }

    public static Profile loadProfile(String profileName) throws FileNotFoundException {
        BufferedReader reader = new BufferedReader(new FileReader(PROFILE_PATH + "\\" + profileName + ".json"));

        return new Gson().fromJson(reader, Profile.class);
    }

    public static String[] getProfileList() {
        File profileDir = new File(JAML.path + "\\profiles\\");
        String[] profileFiles = profileDir.list();
        String[] profileNames = new String[profileFiles.length];
        for (int i = 0; i < profileFiles.length; i++) {
            profileNames[i] = FilenameUtils.removeExtension(profileFiles[i]);
        }
        profileList = profileNames;
        return profileNames;
    }

    public static Profile getActiveProfile() {
        try {
            activeProfile = ProfileUtils.loadProfile(Config.getConfig().getString("launcher.default-profile"));
        } catch (IOException e) {
            System.out.println("Unable to load default profile: " + e.getMessage());
        }
        return activeProfile;
    }
}
