package web.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class ConnectionFactory {

	private static final String DATABASE_PROPERTIES_FILE = "database.properties";

	private static ConnectionFactory instance = new ConnectionFactory();
	private Connection connection;
	
	private ConnectionFactory(){
		renewConnection();
	}

	private void renewConnection() {
		try {
			Properties p = new Properties();

			p.load(getClass().getClassLoader().getResourceAsStream(
					DATABASE_PROPERTIES_FILE));

			String driverClass = p.getProperty("driverClass");
			String url = p.getProperty("url");
			String user = p.getProperty("user");
			String password = p.getProperty("password");

			Class.forName(driverClass);

			connection = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static ConnectionFactory getInstance(){
		return instance;
	}
	
    public Connection getConnection() {
    	if(connection == null) {
    		renewConnection();
    	}
		return connection;
	}
}
