package be.kdg.labyrinth.JavaFX.model;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ScoreModel {
    private int score;

    public ScoreModel() {
        this.score = 0;
    }

    public int getScore() {
        return score;
    }

    public void saveHighscore(long elapsedTime, String difficulty) {
        try {
            List<String> highscores = new ArrayList<>();
            File file = new File("src/be/kdg/labyrinth/HighscoresEasy.txt");
            if (file.exists()) {
                try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        highscores.add(line);
                    }
                }
            }

            // Voeg de nieuwe highscore toe met de moeilijkheidsgraad
            highscores.add(formatTime(elapsedTime) + " (" + difficulty + ")");

            // Sorteer de highscores op tijd
            highscores.sort((t1, t2) -> {
                String[] parts1 = t1.split(" ")[0].split(":");
                String[] parts2 = t2.split(" ")[0].split(":");
                int time1 = Integer.parseInt(parts1[0]) * 3600 + Integer.parseInt(parts1[1]) * 60 + Integer.parseInt(parts1[2]);
                int time2 = Integer.parseInt(parts2[0]) * 3600 + Integer.parseInt(parts2[1]) * 60 + Integer.parseInt(parts2[2]);
                return Integer.compare(time1, time2);
            });

            // Beperk tot maximaal 5 highscores
            if (highscores.size() > 10) {
                highscores = highscores.subList(0, 10);
            }

            // Schrijf de highscores terug naar het bestand
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
                for (String score : highscores) {
                    writer.write(score + "\n");
                }
            }
        } catch (IOException e) {
            System.err.println("Error saving highscore: " + e.getMessage());
        }
    }

    private String formatTime(long millis) {
        int seconds = (int) (millis / 1000) % 60;
        int minutes = (int) ((millis / (1000 * 60)) % 60);
        int hours = (int) ((millis / (1000 * 60 * 60)) % 24);
        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }
}
