package database;

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

import logging.Log;
import logging.LogLevel;

/**
 * connects to postgres database
 * 
 * @author Martin Pabst, 2009
 * 
 */
public class PostgresDatabaseAccess extends DatabaseAccess {

	/**
	 * ip of database-server
	 */
	private String ip;

	/**
	 * port of postgres-server
	 */
	private String port;

	/**
	 * name of database
	 */
	private String databaseName;

	/**
	 * 
	 * @param name
	 * @param username
	 * @param password
	 * @param ip
	 * @param port
	 * @param databaseName
	 */

	public PostgresDatabaseAccess(String name, String username,
			String password, String ip, String port, String databaseName) {
		super(name, username, password);
		this.ip = ip;
		this.port = port;
		this.databaseName = databaseName;
	}

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

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

	}

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

		// Load the driver class
		Class.forName("org.postgresql.Driver");

		// Define the data source for the driver
		String dbURL = "jdbc:postgresql://" + ip + ":" + port + "/"
				+ databaseName;

		// Create a connection through the DriverManager
		connection = DriverManager.getConnection(dbURL, username, password);

		connection.setAutoCommit(false);

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

}
