package database;

import java.awt.Color;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import logging.Log;
import logging.LogLevel;

/**
 * Connects to derby-database
 * 
 * @author Martin Pabst, 2009
 * 
 */
public class DerbyDatabaseAccess extends DatabaseAccess {

	/**
	 * Path to derby database in filesystem
	 */
	private String path;

	public DerbyDatabaseAccess(String name, String username, String password,
			String path) {
		super(name, username, password);
		this.path = path;
	}

	/**
	 * close connection to database
	 */
	@Override
	public void closeConnection() {
		if (connection != null) {
			try {
				/**
				 * close database connection
				 */
				connection.close();

				/**
				 * shutdown database
				 */
				Properties properties = new Properties();
				properties.put("user", username);
				properties.put("password", password);

				DriverManager
						.getConnection(path + ";shutdown=true", properties);

				Log.outColor("Schließe Derby-Datenbank.", LogLevel.useful,
						new Color(0, 150, 0));
			} catch (SQLException e) {
				// Log.outl(
				// "ChangeDatesWorker.closeConnection(): " + e.toString(),
				// LogLevel.error);
			}
		}

	}

	/**
	 * open databse connection
	 */
	@Override
	public void openConnection() throws Exception {
		Log.outColor("Verbinde mit Derby-Datenbank...", LogLevel.useful,
				new Color(0, 150, 0));

		Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

		String path1 = "jdbc:derby:" + path;

		Properties properties = new Properties();
		properties.put("user", username);
		properties.put("password", password);
		properties.put("create", "true");

		connection = DriverManager.getConnection(path1, properties);


		
		Log.outlColor("OK!", LogLevel.useful, new Color(0, 150, 0));
	}

}
