package projet;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class Message extends ParamBD{
    private String login;
    private String contenu;

    public Message() {
    }
    
    public Message(String login, String contenu) {
        this.login = login;
        this.contenu = contenu;
    }

	public String getLogin() {
		return login;
	}

	public void setLogin(String auteur) {
		this.login = auteur;
	}

	public String getContenu() {
		return contenu;
	}

	public void setContenu(String contenu) {
		this.contenu = contenu;
	}
	
	protected static void ajouterMessage(String login,  String contenu) {
		try {
			Connection connexion = DriverManager.getConnection(bdURL, bdLogin, bdPassword);
			String sql = " INSERT INTO message(contenu, login)"
					+ " VALUES (?, ?)"
					+ ";";
			PreparedStatement pst = connexion.prepareStatement(sql);
			pst.setString(1, contenu);
			pst.setString(2, login);
			pst.executeUpdate();

			pst.close();
			connexion.close();
        } catch (SQLException e) {
			e.printStackTrace();
		}	
	}
	
	protected static ArrayList<Message> getListeMessages() {
		ArrayList<Message> messages = new ArrayList<>();

		try {
			Connection connexion = DriverManager.getConnection(bdURL, bdLogin, bdPassword);
			String sql = " SELECT login, contenu"
					+ " FROM message"
					+ ";";
			PreparedStatement pst = connexion.prepareStatement(sql);
			ResultSet rs = pst.executeQuery();
			while(rs.next()) {
				String contenu = rs.getString("contenu");
				String auteur = rs.getString("login");
				
				Message message = new Message(auteur, contenu);
				messages.add(message);
			}
			rs.close();
			pst.close();
			connexion.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return messages;
	}
	
	protected static void effacerMessage() {
		try {
			Connection connexion = DriverManager.getConnection(bdURL, bdLogin, bdPassword);
			String sql = " DELETE FROM message"
					+ ";";
			PreparedStatement pst = connexion.prepareStatement(sql);
			pst.executeUpdate();
			
			pst.close();
			connexion.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}