package oivaltaminen.configuration;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.util.HashMap;
import java.util.stream.Collectors;

import org.json.JSONObject;

public class Configuration {

	private static HashMap<String, String> lastConfiguration = new HashMap<>();
	private static FileTime lastConfigurationRead = null;

	public static void set(String module, String name, Object value) throws IOException {
		Path p = Paths.get(System.getProperty("user.home"), "oivaltaminen", "configuration");
		Files.createDirectories(p);

		JSONObject o = new JSONObject();
		p = p.resolve("configuration.json");
		if (Files.exists(p))
			o = new JSONObject(Files.lines(p).collect(Collectors.joining()));

		if (!o.has(module)) {
			o.accumulate(module, new JSONObject());
		}
		
		JSONObject m = o.getJSONObject(module);
		m.put(name, value);

		Files.write(p, o.toString(2).getBytes());
	}

	public static String get(String module, String name) throws Exception {
		Path p = Paths.get(System.getProperty("user.home"), "oivaltaminen", "configuration", "configuration.json");
		if (!Files.exists(p))
			return null;

		String setting = module + ":" + name;
		if (Files.getLastModifiedTime(p).equals(Configuration.lastConfigurationRead) && Configuration.lastConfiguration.containsKey(setting))
			return Configuration.lastConfiguration.get(setting);

		JSONObject configuration = new JSONObject(Files.lines(p).collect(Collectors.joining()));
		Configuration.lastConfigurationRead = Files.getLastModifiedTime(p);
		if (configuration.has(module) && configuration.getJSONObject(module).has(name)) {
			Configuration.lastConfiguration.put(setting, configuration.getJSONObject(module).getString(name));
			return Configuration.lastConfiguration.get(setting);
		}
		
		return null;
	}
}
