package miningmart.storedProcedures;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DbConnector {

    // If you need debug-messages via System.out.println(..), set to "true":
    private static final boolean debugMessages = false;

    private final Connection con;

	/**
	 * @param dbc is <code>null</code>, if these classes are used as stored procedures.
	 * Otherwise <code>dbc</code> is the thread's <code>miningmart.compiler.utils.Db</code>
	 * object, which is used to request a JDBC connection to the business data schema.
	 * @throws SQLException if the connection cannot be established
	 */
    public DbConnector(BusinessDbConnectionSource dbc) throws SQLException {
		try {
			if (dbc == null) {
			    this.con = DriverManager.getConnection("jdbc:default:connection:");
			}
			else {
				this.con = dbc.getDatabaseConnectionForData();
			}
		}
		catch (Exception e) {
		    throw new SQLException(
		    	"Exception in class miningmart.storedProcedures.DbConnector when trying to connect to DB: "
			   	+ e.getMessage());
		}
		if (this.con == null) {
		    throw new SQLException("Database connection failed!");
		}
    }

    public Connection getConnection() {
		return this.con;
    }

    public void close() {
		final Connection c = this.getConnection();
		try {
		    if (c != null && !c.isClosed()) {
				c.commit();
				c.close();
		    }
		}
		catch (SQLException e) {
	    	infoOutput("Closing Connection in class DbConnector failed:\n" + e);
		}
    }

    public static void infoOutput(String out) {
		if (debugMessages == true) {
		    System.out.println(out);
		}
    }

}
