package controller;

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

import model.MessageAffichage;

public class DataBase {
	
	//Connexion serveur GEI
	//login : tp_servlet_018
	//password : Taey2Aje
	//Plus d'infs connexion sur moodle
	
	private static DataBase instance = null;
	
	public Connection connexion;
	
	private DataBase() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		}catch (ClassNotFoundException e){
			e.printStackTrace();
		}
		try {
			connexion = DriverManager.getConnection("jdbc:mysql://srv-bdens.insa-toulouse.fr:3306/tp_servlet_018?useSSL=false", "tp_servlet_018", "Taey2Aje");
		}catch(SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static DataBase getInstance() {
		synchronized (DataBase.class) {
			DataBase db = instance;
			if(db == null) {
				db = new DataBase();
			}
			return db;
		}
	}
	
	//Ajout d'un user 
	//retourne l'id associé au user ajouté
	public int addUser(String pseudo, String login) {
		String query = "INSERT INTO users (pseudo, statut, login) VALUES (?, ?, ?)";
		PreparedStatement pStat = null;
		try {
			pStat = connexion.prepareStatement(query);
			pStat.setString(1, pseudo);
			pStat.setString(2, "En ligne");
			pStat.setString(3, login);
			pStat.executeUpdate();
		}catch (SQLException e) {
			e.printStackTrace();
		}
		query = "SELECT * FROM users WHERE pseudo=?";
		int id =0;
		try {
			pStat = connexion.prepareStatement(query);
			pStat.setString(1, pseudo);
			ResultSet resId = pStat.executeQuery();
			if(resId.first()) {
				id = resId.getInt("id");
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}
		return id;
	}

	public String getPseudoFromId(int id) {
		String pseudo = null;
		String query = "SELECT * FROM users WHERE id=?";
		PreparedStatement pStat = null;
		try {
			pStat = connexion.prepareStatement(query);
			pStat.setInt(1, id);
			ResultSet resPseudo = pStat.executeQuery();
			if(resPseudo.first()) {
				pseudo = resPseudo.getString("pseudo");
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}
		return pseudo;
	}
	
	public int getIdFromPseudo(String pseudo) {
		int id = -1;
		String query = "SELECT * FROM users WHERE pseudo='" + pseudo + "' AND statut = 'En ligne'";
		PreparedStatement pStat = null;
		try {
			pStat = connexion.prepareStatement(query);
			//pStat.setString(1, pseudo);
			ResultSet resId = pStat.executeQuery();
			if(resId.next()) {
				id = resId.getInt(1);
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}
		return id;
	}
	
	public boolean loginExiste(String login) {
        String loginAux = null;
        String query = "SELECT * FROM users WHERE login =?";
        PreparedStatement pStat = null;
        try {
			pStat = connexion.prepareStatement(query);
		    pStat.setString(1, login);
	        ResultSet rs = pStat.executeQuery();
	        if (rs.first()) {
	            loginAux = rs.getString("login");
	        }
		} catch (SQLException e) {
			e.printStackTrace();
		}
        return !(loginAux==null);
	}
	
	public String getPseudoFromLogin(String login) {
		String pseudo = null;
		String query = "SELECT * FROM users WHERE login=?";
		PreparedStatement pStat = null;
		try {
			pStat = connexion.prepareStatement(query);
			pStat.setString(1, login);
			ResultSet resPseudo = pStat.executeQuery();
			if(resPseudo.first()) {
				pseudo = resPseudo.getString("pseudo");
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}
		return pseudo;
	}
	
	public int getIdFromLogin(String login) {
		int id = -1;
		String query = "SELECT * FROM users WHERE login=?";
		PreparedStatement pStat = null;
		try {
			pStat = connexion.prepareStatement(query);
			pStat.setString(1, login);
			ResultSet resPseudo = pStat.executeQuery();
			if(resPseudo.first()) {
				id = resPseudo.getInt("id");
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}
		return id;
	}
	
	public void deleteFromId(int id) {
		String query = "DELETE FROM `users` WHERE `id` = ?";
		PreparedStatement pStat = null;
		try {
			pStat = connexion.prepareStatement(query);
			pStat.setInt(1, id);
			pStat.executeUpdate();
		}catch(SQLException e) {
			e.printStackTrace();
		}
		
	}
	
	public void updatePseudo(int id, String pseudo) {
		String query = "UPDATE `users` SET `pseudo`=? WHERE id=?";
		PreparedStatement pStat = null;
		try {
			pStat = connexion.prepareStatement(query);
			pStat.setString(1, pseudo);
			pStat.setInt(2, id);
			pStat.executeUpdate();
		}catch(SQLException e) {
			e.printStackTrace();
		}
	}
	
	//chat table : 
	//nom : idSrcidDest
    //colonnes :
    //id (l'id unique du message)
    //idSrc et idDest : les id des deux users qui se parlent
    //message : le message envoyé 
    //date : la date d'envoi du msg
    public void newChatTable (int id1, int id2) {
        int idSrc = id1;
        int idDest = id2;
        if(id1>id2) {
            idSrc = id2;
            idDest = id1;
        }
        String nameTable = idSrc+"_"+idDest;
        String query = "CREATE TABLE " +nameTable+" (\n" +
        "id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, \n" +
        "idSrc INT NOT NULL,\n" + 
        "idDest INT NOT NULL,\n" +
        "message MEDIUMTEXT NOT NULL,\n" +
        "date_heure TIMESTAMP NOT NULL\n" +
        ");";
        PreparedStatement pStat = null;
        try {
            pStat = connexion.prepareStatement(query);
            pStat.executeUpdate();
        }catch(SQLException e) {
            e.printStackTrace();
        }

    }
    
    public boolean tableChatExists(int id1, int id2) {
        int idSrc = id1;
        int idDest = id2;
        boolean res = true;
        if(id1>id2) {
            idSrc = id2;
            idDest = id1;
        }
        String nameTable = idSrc+"_"+idDest;
        String query = "SELECT * FROM " + nameTable;
        PreparedStatement pStat = null;
        try {
            pStat = connexion.prepareStatement(query);
            pStat.executeQuery();
        }catch(SQLException e) {
            res = false;
            //e.printStackTrace();
        }
        return res;
    }
    
    //il faut mettre dans l'ordre idSrc pour id1 et id Dest pour id2 dans les params
    public void addMessage(int id1, int id2, String message) {
        int idSrc = id1;
        int idDest = id2;
        if(id1>id2) {
            idSrc = id2;
            idDest = id1;
        }
        String nameTable = idSrc+"_"+idDest;
        String query = "INSERT INTO " + nameTable + "(idSrc, idDest, message, date_heure) VALUES (?, ?, ?, CURRENT_TIME)";
        PreparedStatement pStat = null;
        try {
            pStat = connexion.prepareStatement(query);
            pStat.setInt(1, id1);
            pStat.setInt(2, id2);
            pStat.setString(3, message);
            pStat.executeUpdate();
        }catch(SQLException e) {
            e.printStackTrace();
        }
    }
    
   public ArrayList<MessageAffichage> getHistoric(int id1, int id2) throws SQLException{
		ArrayList<MessageAffichage> result = new ArrayList<MessageAffichage>();
		int idFirst;
        int idSecond;
        if (id1 > id2) {
            idSecond = id1;
            idFirst = id2;
        } else {
            idSecond = id2;
            idFirst = id1;
        }
		String nameTable = idFirst+"_"+idSecond;
		String preparedQuery = "SELECT * FROM " + nameTable;
        PreparedStatement prSt = null;
		try {
			prSt = connexion.prepareStatement(preparedQuery);
            ResultSet rs = prSt.executeQuery();
			while (rs.next()) {
				MessageAffichage msg = new MessageAffichage(rs.getString(4), rs.getInt(2), rs.getInt(3));
                result.add(msg);
			}
			rs.close();
			prSt.close();
		}catch (SQLException throwables) {
            throwables.printStackTrace();
		}
		return result;
    }
   
   public Timestamp getDateFromMessage(int id1, int id2, String message) {
       Timestamp date = null;
       int idSrc = id1;
    int idDest = id2;
    if(id1>id2) {
        idSrc = id2;
        idDest = id1;
    }
    String nameTable = idSrc+"_"+idDest;
    String query = "SELECT * FROM "+nameTable+" WHERE message=?";
    PreparedStatement pStat = null;
    try {
        pStat = connexion.prepareStatement(query);
        pStat.setString(1, message);
        ResultSet resPseudo = pStat.executeQuery();
        if(resPseudo.first()) {
            date = resPseudo.getTimestamp("date_heure");
        }
    }catch(SQLException e) {
        e.printStackTrace();
    }
    return date;
}
   
   public void updateStatus(int id, String status) {
		String query = "UPDATE `users` SET `statut`=? WHERE id=?";
		PreparedStatement pStat = null;
		try {
			pStat = connexion.prepareStatement(query);
			pStat.setString(1, status);
			pStat.setInt(2, id);
			pStat.executeUpdate();
		}catch(SQLException e) {
			e.printStackTrace();
		}
	}
}