package org.aegee.runanddine.util.data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * SQL connection manager for SQL connections (can be used as registry for multiple connections)
 * 
 * @author Sebastian Fuchs
 */
public class ConnectionManager
{
	/**
	 * Address of the host for the connection
	 */
	private String host;

	/**
	 * Database name for the connection
	 */
	private String database;

	/**
	 * Username for the database
	 */
	private String username;

	/**
	 * Password for the database
	 */
	private String password;

	/**
	 * SQL Connection
	 */
	private Connection con = null;

	/**
	 * Registry for SQL connections
	 */
	private static Map<String, Connection> registry = new HashMap<String, Connection>();

	/**
	 * Setup SQL connection with given parameters
	 * 
	 * @param host
	 *            Host name
	 * @param database
	 *            Database name
	 * @param username
	 *            Username for database
	 * @param password
	 *            Password for database
	 */
	public ConnectionManager(String host, String database, String username, String password)
	{
		this.host = host;
		this.database = database;
		this.username = username;
		this.password = password;
		this.establishConnection();
	}

	/**
	 * Establish connection to SQL database
	 */
	private void establishConnection()
	{
		try
		{
			Class.forName("com.mysql.jdbc.Driver");
			this.con = DriverManager.getConnection("jdbc:mysql://" + this.host + "/" + this.database + "?user="
				+ this.username + "&password=" + this.password + "&autoReconnect=true");
		}
		catch (ClassNotFoundException e)
		{
			// @TODO: handle exception
		}
		catch (SQLException e)
		{
			// @TODO: handle exception
		}
	}

	/**
	 * Return SQL connection of current CM instance
	 * 
	 * @return SQL connection
	 */
	public Connection getConnection()
	{
		return this.con;
	}

	/**
	 * Make SQL connection globally available under given name
	 * 
	 * @param name
	 *            Global name for connection
	 * @param con
	 *            Connection to be stored in registry
	 */
	public static void setConnection(String name, Connection con)
	{
		ConnectionManager.registry.put(name, con);
	}

	/**
	 * Return SQL connection identified by given name
	 * 
	 * @param name
	 *            Global name of connection
	 * @return SQL connection for given name
	 * @throws ConnectionNotFoundException
	 */
	public static Connection getConnection(String name) throws ConnectionNotExistingException
	{
		// check if connection exists in registry
		if (!ConnectionManager.registry.containsKey(name))
		{
			throw new ConnectionNotExistingException();
		}

		return ConnectionManager.registry.get(name);
	}
}
