package io.gitlab.jfronny.inceptum.launcher.system.instance; import io.gitlab.jfronny.commons.cache.FileBackedRef; import io.gitlab.jfronny.commons.io.JFiles; import io.gitlab.jfronny.commons.throwable.ThrowingConsumer; import io.gitlab.jfronny.inceptum.common.MetaHolder; import io.gitlab.jfronny.inceptum.common.Utils; import io.gitlab.jfronny.inceptum.launcher.model.inceptum.InstanceMeta; import io.gitlab.jfronny.inceptum.launcher.system.instance.Instance; import java.io.Closeable; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; public class InstanceList { private static final Map metas = new LinkedHashMap<>(); public static void reset() { synchronized (metas) { for (IEntry value : metas.values()) { try { value.close(); } catch (IOException e) { Utils.LOGGER.error("Could not close reference to instance meta", e); } } metas.clear(); } } public static void forEach(ThrowingConsumer target) throws IOException, TEx { Objects.requireNonNull(target); if (!Files.exists(MetaHolder.INSTANCE_DIR)) Files.createDirectories(MetaHolder.INSTANCE_DIR); try { JFiles.listTo(MetaHolder.INSTANCE_DIR, path -> { if (!Files.isDirectory(path)) return; target.accept(read(path)); }); } catch (Exception e) { //noinspection unchecked throw (TEx) e; } } public static boolean isEmpty() throws IOException { if (!Files.exists(MetaHolder.INSTANCE_DIR)) return true; return JFiles.list(MetaHolder.INSTANCE_DIR, Files::isDirectory).isEmpty(); } public static Instance read(Path instancePath) throws IOException { Objects.requireNonNull(instancePath); synchronized (metas) { if (!metas.containsKey(instancePath)) { metas.put(instancePath, new IEntry( instancePath, new FileBackedRef<>(instancePath.resolve("instance.json"), InstanceMeta.class) )); } return metas.get(instancePath).toPub(); } } private record IEntry(Path path, FileBackedRef meta) implements Closeable { @Override public String toString() { return path.getFileName().toString(); } public Instance toPub() throws IOException { return new Instance(path, meta.get()); } @Override public void close() throws IOException { meta.close(); } } }