import java.sql.*;

/**
 *  The DBConnection class uses JDBC to connect to an HSQL database
 */

public class DBConnection {

    /** 
     * DRIVER holds path to JDBC driver
     */
    private static final String DRIVER = "org.hsqldb.jdbcDriver";

    /**
     * DATABASE is the database to use
     */
    private static String database;

    /**
     * PREFIX is the database URL PREFIX
     */
    private static final String PREFIX = "jdbc:hsqldb:";

    /**
     * USER is the database user's user id
     */
    private static final String USER = "sa";

    /**
     * PASSWORD is the database user's password
     */
    private static final String PASSWORD = "";

    /**
     * Connection is the database connection object returned by JDBC
     */
    private static Connection theConnection = null;

    /**
     *  The DBConnection constructor loads the driver and makes the database
     *  connection.  It is private to force the use of the getConnection method.
     */
	
    private DBConnection() {

	// Load the JDBC driver

        try { 
            Class.forName(DRIVER); 
        } 
	catch (ClassNotFoundException ex) { 
	    System.out.println("Failed to find driver class.");
	    return;
        }

	// Make the connection

	try {
	    theConnection = 
		DriverManager.getConnection(PREFIX + database, USER, PASSWORD);
	    System.out.println("DB connection successful.");
	}
	catch (SQLException e) {
	    System.out.println("DB connection failed.");
	    System.out.println(e.getMessage());
	    e.printStackTrace();
	    return;
	}

    } // private DBConnection()


    /**
     *  getConnection is a class method that will retrieve the database 
     *  connection, creating a new one if necessary.  This is the only way
     *  outside classes can connect to the database.
     *  @param db database location
     *  @return the connection to the database
     */

    public static Connection getConnection(String db) {
	database = db;
	try {
	    if (theConnection == null || theConnection.isClosed())
		new DBConnection();
	}
	catch (SQLException ex) {
	    System.out.println(ex.getMessage());
	    ex.printStackTrace();
	}
	return theConnection;
    }


    /**
     *  DBConnection.disConnect() closes the connection if it is not null
     */
    public static void disConnect() {
	if (theConnection != null) {
	    try {
		theConnection.close();
		System.out.println("DB connection closed.");
	    }
	    catch (SQLException e) {
		System.out.println("DB connection failed to close.");
		e.printStackTrace();
	    }
	}
    }  // public void disConnect()

}