package it.cavallium; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.time.Duration; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.event.Level; public class SettingsServiceImpl implements SettingsService { private static final Gson gson = new Gson(); private final AtomicReference delayBetweenAdds = new AtomicReference<>(Duration.ZERO); public SettingsServiceImpl() { synchronized (gson) { if (Files.exists(Paths.get("settings.json"))) { try { var settings = gson.fromJson(Files.readString(Paths.get("settings.json"), StandardCharsets.UTF_8), JsonObject.class); if (settings != null) { Optional.ofNullable(settings.getAsJsonPrimitive("delayBetweenAdds")).ifPresent(seconds -> { this.delayBetweenAdds.set(Duration.ofSeconds(seconds.getAsInt())); }); } } catch (Exception e) { e.printStackTrace(); }; } } } private void saveSettings() { synchronized (gson) { var settings = new JsonObject(); settings.addProperty("delayBetweenAdds", delayBetweenAdds.get().toSeconds()); try { Files.writeString(Paths.get("settings.json"), gson.toJson(settings), StandardCharsets.UTF_8, StandardOpenOption.CREATE); } catch (IOException e) { App.getLogService().append(Level.ERROR, e.getLocalizedMessage()); } } } @Override public void setDelayBetweenAdds(Duration duration) { delayBetweenAdds.set(duration); saveSettings(); } @Override public Duration getDelayBetweenAdds() { return delayBetweenAdds.get(); } }