
package uy.edu.udelar.forrest.forrestloganalyser.model;

import java.sql.Connection;
import java.sql.DriverManager;

import uy.edu.udelar.forrest.forrestloganalyser.exceptions.DataBaseConnectionException;

public class DataBase {
    private String url;
    private String driver;
    private String password;
    private String user;
    private Connection connection;

    public DataBase(){
        url="";
        driver="";
        password="";
        user="";
        connection=null;
    }
    
    public DataBase(String _url, String _driver, String _user,  String _password)  throws DataBaseConnectionException {
        url=_url;
        driver=_driver;
        password=_password;
        user=_user;
        if (connection==null){
            makeConnection();
        }
    }
    
    public Connection getConnection(){
        return connection;
    }
    
    public synchronized void makeConnection() throws DataBaseConnectionException {
        try {
            Class.forName(driver).newInstance();
            try {
                connection = DriverManager.getConnection(url, user, password);
            } catch (Exception e) {
                throw new DataBaseConnectionException("DataBase::makeConnection - Error al conectarse con la base - " + e.getMessage());
            }
        }catch (DataBaseConnectionException e){
            throw e;
        }catch (Exception e) {
            throw new DataBaseConnectionException("DataBase::makeConnection - Error al cargar la clase - " + driver + " - " + e.getMessage());
        }
    }

    public synchronized void closeConnection() throws DataBaseConnectionException {
        try{
            connection.close();
        }catch (Exception e) {
            throw new DataBaseConnectionException("DataBase::closeConnection - Error al Cerrar la conexion - " + e.getMessage());
        }
    }

}
