package de.ugoe.cs.swe.memos.database;

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

import de.ugoe.cs.swe.memos.SettingsManager;

public class MySQLConnector {

	private final String driver = "com.mysql.jdbc.Driver";
	private final String prefix = "jdbc:mysql://";

	private String databaseURL;
	private String databaseUser;
	private String databasePassword;

	private static MySQLConnector instance;
	private Connection connection;

	public Connection getConnection() {
		try {
			if (!this.isConnected())

				this.connect();
		} catch (Exception e) {
			System.out.println(e.getMessage());
			/* TODO: INSERT FANCY CODE HERE */
		}

		return connection;
	}

	private void init() {
		this.databaseURL = SettingsManager.getInstance().getDatabaseURI();
		this.databaseUser = SettingsManager.getInstance().getUsername();
		this.databasePassword = SettingsManager.getInstance().getPassword();
	}

	private MySQLConnector() {
		init();
	}

	public static MySQLConnector getInstance() {
		if (MySQLConnector.instance == null) {
			MySQLConnector.instance = new MySQLConnector();
		}

		return MySQLConnector.instance;
	}

	public boolean isConnected() throws SQLException {
		return (this.connection != null && !this.connection.isClosed());
	}

	public void connect() throws DatabaseException, SQLException {
		if (this.isConnected())
			this.close();

		try {

			Properties p = new Properties();
			//
			p.setProperty("user", databaseUser);
			p.setProperty("password", databasePassword);
			p.setProperty("jdcbCompliantTruncation", "false");

			if (SettingsManager.getInstance().getSSLEnabled()) {

				System.setProperty("javax.net.ssl.trustStore", SettingsManager.getInstance().getSSLKeyName());
				System.setProperty("javax.net.ssl.trustStorePassword","huttraeger");

				p.setProperty("useSSL", "true");
			}

			Class.forName(driver).newInstance();
			
			this.databaseURL = SettingsManager.getInstance().getDatabaseURI();
			this.connection = DriverManager.getConnection(this.prefix
					.concat(this.databaseURL), p);
			this.connection.setAutoCommit(true);

		} catch (Exception e) {
			System.out.println(e.toString());
			e.printStackTrace();
			throw new DatabaseException(e.getMessage());

		}
	}

	public void close() throws DatabaseException, SQLException {
		if (connection != null)
			try {
				this.connection.close();
				this.connection = null;
				// ignored in code coverage. not injectable sql error :))
			} catch (Exception e) {
				throw new DatabaseException(e.getMessage());
			}
	}

}
