package se.urmo.game.main;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class HighScoreManager {
    private final Path file = Path.of("highscores.dat");
    private final int maxEntries = 10;
    private final List<Integer> scores = new ArrayList<>();

    public HighScoreManager() { load(); }

    public void submit(int score) {
        scores.add(score);
        scores.sort(Comparator.reverseOrder());
        if (scores.size() > maxEntries) scores.remove(scores.size() - 1);
        save();
    }

    public List<Integer> top() { return List.copyOf(scores); }

    private void load() {
        try {
            if (!Files.exists(file)) return;
            for (String line : Files.readAllLines(file)) {
                scores.add(Integer.parseInt(line.trim()));
            }
            scores.sort(Comparator.reverseOrder());
        } catch (Exception ignored) {}
    }

    private void save() {
        try {
            var lines = scores.stream().map(String::valueOf).toList();
            Files.write(file, lines, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
        } catch (Exception ignored) {}
    }
}
