import java.sql.*;

public class Vote {
    public static void main(String[] args) {
        if (args.length < 1) {
            System.err.println("No country given.");
            return;
        }

        try {
            Class.forName("org.mariadb.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            System.err.println("MariaDB driver not found");
            return;
        }
        
        Connection cnx;
        try {
            cnx = DriverManager.getConnection("jdbc:mariadb://dwarves.iut-fbleau.fr/horville", "horville", "a5gc95");
        } catch (SQLException ex) {
            System.err.println("Unable to access Database.");
            return;
        }
        
        try {
            PreparedStatement nameReq = cnx.prepareStatement("SELECT ID FROM Pays WHERE Nom = (?);");
            nameReq.setString(1, args[0]);
            nameReq.executeUpdate();

            ResultSet rs1 = nameReq.executeQuery();
            rs1.next();
            String nom = rs1.getString(1);
            rs1.close();

            PreparedStatement req = cnx.prepareStatement("SELECT Nom, Points FROM Vote LEFT JOIN Pays ON Vote.Votants = Pays.ID WHERE Competiteur = (?);");
            req.setString(1, nom);
            req.executeUpdate();

            int total = 0;
            ResultSet rs = req.executeQuery();
            while (rs.next()) {
                String country = rs.getString(1);
                int score = rs.getInt(2);

                total += score;

                System.out.println(country + "  " + score);
            }

            System.out.println("            ---");
            System.out.println("Total        " + total);

            rs.close();
            req.close();
            
        } catch (SQLException ex) {
            System.err.println("SQL Request exception.");
            System.err.println (ex);
        }

        try {
            cnx.close();
        } catch (SQLException ex) {
            System.err.println("Unable to close connection.");
        }
    }
}