//	Contour - Android drawing teacher application
//	Copyright (C) 2014  Johannes Riedmann
//	
//	This program is free software: you can redistribute it and/or modify
//	it under the terms of the GNU General Public License as published by
//	the Free Software Foundation, either version 3 of the License, or
//	(at your option) any later version.
//	
//	This program is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//	GNU General Public License for more details.
//	
//	You should have received a copy of the GNU General Public License
//	along with this program.  If not, see <http://www.gnu.org/licenses/>.

package com.j0h1.contour.server;

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

import javax.swing.JOptionPane;

/**
 * Singleton class to handle HSQLDB database access.
 * @author Johannes Riedmann
 *
 */
public class DatabaseManager {

	private static DatabaseManager dbm;
	private Connection connection;
	
	protected DatabaseManager() {
		dbm = this;
	}
	
	/**
	 * Creates/returns existing instance of DatabaseManager.
	 * @return Instance of DatabaseManager.
	 */
	public static DatabaseManager getInstance() {
		if (dbm == null)
			return new DatabaseManager();
		return dbm;
	}
	
	/**
	 * Opens a connection to HSQLDB-Database.
	 */
	public void openConnection() {
		// load the SQLite JDBC driver using the current class loader
	    try {
			Class.forName("org.hsqldb.jdbcDriver");
			
			try {
		    	connection = DriverManager.
		    			getConnection("jdbc:hsqldb:hsql://localhost/ContourDB", "SA", "");
			} catch (SQLException e) {
				JOptionPane.showMessageDialog(null, "Database server not started?");
			}
		} catch (ClassNotFoundException e1) {
			JOptionPane.showMessageDialog(null, "HSQLDB-JDBC driver not found.");
		}
	}
	
	public Connection getConnection() {
		return connection;
	}
	
	/**
	 * Closes connection to database.
	 */
	public void closeConnection() {
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				JOptionPane.showMessageDialog(null, "Unable to close database connection.");
			}
			connection = null;
		}		
	}
}
