package fr.insa.clavardator.client.config;

import fr.insa.clavardator.lib.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class ConfigLoader {

	public static final String PATH = "config.json";

	public static void load(ConfigLoadedCallback callback) {
		new Thread(() -> {
			try {
				InputStream is = new FileInputStream(PATH);
				JSONTokener tokener = new JSONTokener(is);
				JSONObject obj = new JSONObject(tokener);
				callback.onLoaded(new Config(obj));
			} catch (FileNotFoundException e) {
				Log.v("CONFIG", "No config file found");
				callback.onLoaded(new Config());
			} catch (JSONException e) {
				Log.v("CONFIG", "Could not read config file. Please make sure it is a valid JSON.");
				callback.onLoaded(new Config());
			}
		}).start();
	}

	public interface ConfigLoadedCallback {
		void onLoaded(Config config);
	}

}
