package org.biomoby.registry.rdfagent.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;

import org.biomoby.registry.properties.MobyCentralConfig;
import org.biomoby.shared.MobyException;

/**
 * @author Edward Kawas
 * 
 * Establish a connection with a database
 */

public class DBConnector {

	private Connection connection = null;

	/**
	 * Constructor
	 * @throws MobyException if the JDBC driver was not found
	 */
	public DBConnector() throws MobyException  {
		Log.info("Loading the JDBC driver");
		try {
			// Load the JDBC driver
			String driverName = "com.mysql.jdbc.Driver";
			Class.forName(driverName);
		} catch (ClassNotFoundException e) {
			Log.exception(this.getClass().getName(), "DBConnector()", e);
			Log.severe(e.getLocalizedMessage());
			throw new MobyException(
					"Could not find database driver. Please ensure that you have the right libraries present");
		}
		Log.info("Successfully loaded the JDBC driver.");

	}

	/**
	 * 
	 * @return a Connection object to the database
	 * @throws MobyException if there is an  database access error
	 */
	public Connection getConnection() throws MobyException {
		if (this.connection != null)
			return this.connection;
		Log.info("Trying to get a connection to the DB using the JDBC driver.");
		try {
			// get certain properties from mobycentral.config
			Map map = MobyCentralConfig.getMobyCentral();
			// Create a connection to the database
			String serverName = map.get("url") + ":" + map.get("port");
			String mydatabase = (String) map.get("dbname");// "mobyobject";
			String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
			String username = (String) map.get("username");// "moby_external";
			String password = (String) map.get("password");// "";
			this.connection = DriverManager.getConnection(url, username,
					password);
		} catch (SQLException e) {
			Log.exception(this.getClass().getName(), "getConnection()", e);
			Log.severe(e.getLocalizedMessage());
			throw new MobyException("Database access error.");
		}
		Log.info("Successfully retrieved a connection.");
		return this.connection;
	}
	
	/**
	 * close the connection to the database
	 *
	 */
	public void closeConnection() {
		Log.info("Attempting to close the database connection.");
		if (this.connection != null) {
			try {
				this.connection.close();
				Log.info("Database connection is closed.");
				this.connection = null;
			} catch (SQLException e) {
				Log.exception(this.getClass().getName(), "closeConnection()", e);
				Log.severe(e.getLocalizedMessage());
			}
			return;
		}
		Log.info("Connection may not need closing (did you already do this?).");
		
	}
}
