package linea;

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

public class GestionBDD {

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

    //connexion bdd
    private static Connection connecter() throws SQLException {
        return DriverManager.getConnection(URL);
    }

    //creation de la table score a ca premiere execution
    public static void creerTableSiAbsente() {

        String sql = """
                CREATE TABLE IF NOT EXISTS scores (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    score INTEGER NOT NULL,
                    date TEXT NOT NULL
                );
                """;

        try (Connection connexion = connecter();
             Statement statement = connexion.createStatement()) {

            statement.execute(sql);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // Ajouter un score a la fin de la partie 
    public static void ajouterScore(int score) {

        String sql = "INSERT INTO scores(score, date) VALUES(?, ?)";

        try (Connection connexion = connecter();
             PreparedStatement requete = connexion.prepareStatement(sql)) {

            requete.setInt(1, score);
            requete.setString(2, java.time.LocalDate.now().toString());

            requete.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // Récupérer tous les scores
    public static List<Integer> recupererTousLesScores() {

        List<Integer> listeScores = new ArrayList<>();

        String sql = "SELECT score FROM scores ORDER BY date DESC";

        try (Connection connexion = connecter();
             Statement statement = connexion.createStatement();
             ResultSet resultat = statement.executeQuery(sql)) {

            while (resultat.next()) {
                listeScores.add(resultat.getInt("score"));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return listeScores;
    }

    // Récupérer le meilleur score
    public static int recupererMeilleurScore() {

        String sql = "SELECT MAX(score) AS meilleur FROM scores";

        try (Connection connexion = connecter();
             Statement statement = connexion.createStatement();
             ResultSet resultat = statement.executeQuery(sql)) {

            if (resultat.next()) {
                return resultat.getInt("meilleur");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return 0;
    }
}
