package linea;

import java.sql.*;

public class GestionnaireScore {

    private static final String URL = "jdbc:sqlite:linea_bdd.db";

    public GestionnaireScore() {
        try {
            Class.forName("org.sqlite.JDBC");
        } catch (ClassNotFoundException e) {
            System.err.println("[BDD] Impossible de charger le driver SQLite.");
            e.printStackTrace();
        }
    }

    public void sauvegarderScore(String nom, int points) {
        if (nom == null || nom.trim().isEmpty()) {
            return;
        }

        String sql = "INSERT INTO scores(nom, points) VALUES(?, ?)";

        try (Connection conn = DriverManager.getConnection(URL);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, nom.trim());
            pstmt.setInt(2, points);
            pstmt.executeUpdate();

        } catch (SQLException e) {
            System.err.println("[BDD] Erreur lors de l'enregistrement du score.");
            e.printStackTrace();
        }
    }

    public String getTopScores() {
        StringBuilder sb = new StringBuilder("--- TOP 10 SCORES ---\n");
        String sql = "SELECT nom, points FROM scores ORDER BY points DESC LIMIT 10";

        try (Connection conn = DriverManager.getConnection(URL);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            boolean auMoinsUn = false;

            while (rs.next()) {
                auMoinsUn = true;
                sb.append(rs.getString("nom"))
                        .append(" : ")
                        .append(rs.getInt("points"))
                        .append("\n");
            }

            if (!auMoinsUn) {
                sb.append("(Aucun score enregistré pour le moment)\n");
            }

        } catch (SQLException e) {
            System.err.println("[BDD] Erreur lors de la lecture des scores.");
            e.printStackTrace();
            return "Erreur lors de la lecture des scores.";
        }

        return sb.toString();
    }
}