package thb.jeanluc.adventure.save;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

/** Loads/saves {@link Settings} as JSON (default {@code saves/settings.json}). */
@Slf4j
public class SettingsStore {

    private final Path file;
    private final ObjectMapper mapper = new ObjectMapper();

    public SettingsStore() {
        this(Path.of("saves", "settings.json"));
    }

    public SettingsStore(Path file) {
        this.file = file;
    }

    /** Returns persisted settings, or {@link Settings#defaults()} on any problem. */
    public Settings load() {
        if (!Files.isRegularFile(file)) {
            return Settings.defaults();
        }
        try {
            return mapper.readValue(file.toFile(), Settings.class);
        } catch (IOException e) {
            log.warn("Could not read settings {}, using defaults", file, e);
            return Settings.defaults();
        }
    }

    /** Persists settings; logs and swallows failures (non-fatal). */
    public void save(Settings settings) {
        try {
            if (file.getParent() != null) {
                Files.createDirectories(file.getParent());
            }
            mapper.writerWithDefaultPrettyPrinter().writeValue(file.toFile(), settings);
        } catch (IOException e) {
            log.warn("Could not write settings {}", file, e);
        }
    }
}
