package database;

import java.sql.Connection;

/**
 * Gathers login-information for a database-connection from XML-Element, stores
 * this information and connects to database
 * 
 * This class is overridden by classes specialized for one database type
 * 
 * @author Martin Pabst, 2009
 * 
 */

public abstract class DatabaseAccess {

	/**
	 * identifier of this connection
	 */
	protected String name;

	/**
	 * database-username
	 */
	protected String username;

	/**
	 * password for database user
	 */
	protected String password;

	/**
	 * database connection
	 */
	protected Connection connection;

	/**
	 * stores active asv-database
	 */
	private static DatabaseAccess activeASVDatabase;

	/**
	 * stores active asv-database
	 */
	private static DatabaseAccess activeCacheDatabase;

	/**
	 * 
	 * cache = true => database to cache names in cache = false => asv database
	 * 
	 * @param cache
	 * @return
	 */
	public static DatabaseAccess getActiveDatabase(boolean cache) {
		if (cache) {
			return activeCacheDatabase;
		} else {
			return activeASVDatabase;
		}
	}

	public static void setActiveDatabase(DatabaseAccess activeDatabase) {
		DatabaseAccess.activeASVDatabase = activeDatabase;
	}

	/**
	 * open database connection
	 * 
	 * @throws Exception
	 */
	public abstract void openConnection() throws Exception;

	/**
	 * close database connection
	 */
	public abstract void closeConnection();

	/**
	 * returns connection-object to database
	 * 
	 * @return
	 */
	public Connection getConnection() {
		try {
			connection.setAutoCommit(true);
		} catch (Exception ex) {
		}
		return connection;
	}

	public DatabaseAccess(String name, String username, String password) {

		this.username = username;
		this.password = password;
		this.name = name;
	}

	public static void setActiveASVDatabase(DatabaseAccess activeASVDatabase) {
		DatabaseAccess.activeASVDatabase = activeASVDatabase;
	}

	public static void setActiveCacheDatabase(DatabaseAccess activeCacheDatabase) {
		DatabaseAccess.activeCacheDatabase = activeCacheDatabase;
	}

}
