mcexts/src/main/java/net/flashii/mcexts/Config.java
2023-08-23 01:43:53 +02:00

72 lines
2 KiB
Java

package net.flashii.mcexts;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import net.fabricmc.loader.api.FabricLoader;
public class Config {
static class ConfigCache {
private static final long CACHE_TIMEOUT = 300000;
public long readTime;
public String contents;
public ConfigCache(String contents) {
this.readTime = System.currentTimeMillis();
this.contents = contents;
}
public boolean needsRefresh() {
return readTime < System.currentTimeMillis() - CACHE_TIMEOUT;
}
}
private static Path configPath = null;
private static HashMap<String, ConfigCache> cache = new HashMap<>();
private static Path getConfigPath() {
if(configPath == null)
configPath = FabricLoader.getInstance().getGameDir().resolve("config").resolve("fiiexts");
return configPath;
}
private static Path getConfigPath(String name) {
return getConfigPath().resolve(name);
}
public static String getValue(String name) {
return getValue(name, null);
}
public static String getValue(String name, String fallback) {
return getFileContentsCached(getConfigPath(name), fallback);
}
private static String getFileContentsCached(Path path, String fallback) {
String output = null;
String pathStr = path.toString();
if(cache.containsKey(pathStr)) {
ConfigCache cached = cache.get(pathStr);
if(!cached.needsRefresh())
output = cached.contents;
}
if(output == null) {
try {
output = Files.exists(path) ? Files.readString(path).trim() : fallback;
} catch(IOException ex) {
ex.printStackTrace();
output = fallback;
}
cache.put(pathStr, new ConfigCache(output));
}
return output;
}
}