package search;

import java.sql.SQLException;
import chemaxon.jchem.db.StructureTableOptions;
import chemaxon.jchem.db.TableTypeConstants;
import chemaxon.jchem.db.UpdateHandler;
import chemaxon.util.ConnectionHandler;

/**
 * Example codes for creating a database table
 * 
 * There are mandatory parameters for creating a database table:
 * open connection handler, name of database table to create, table type.
 * 
 * Since fingerprint parameters are not set by default,
 * they must also be set according to table type, using pre-defined
 * constant arrays of UpdateHandler class.
 * 
 * @author Peter Kovacs
 * @author Tamas Csizmazia
 * @version 5.0.3, 04/26/2008
 * 
 */
public class TableOperations {

    /**
     * Creates a default (Molecule) type database table.
     * 
     * @param connectionHandler an open connection handler to database
     * @param structTableName table name
     * @throws SQLException: table cannot be created
     */
    public static void createDatabaseTable(ConnectionHandler connectionHandler,
	    String structTableName) 
    	throws SQLException {
	
	// creating default table type
	createDatabaseTable(connectionHandler, structTableName,
		TableTypeConstants.TABLE_TYPE_DEFAULT);
    }

    /**
     * Creates a database table of given type.
     * 
     * @param connectionHandler an open connection handler to database
     * @param structTableName table name
     * @param tableType table type
     * @throws SQLException: table cannot be created
     */
    public static void createDatabaseTable(ConnectionHandler connectionHandler,
	    String structTableName, int tableType) 
    	throws SQLException {

	// dropping existing structure table
	try {
	    UpdateHandler.dropStructureTable(connectionHandler,
		    structTableName);
	} catch (SQLException sqlException) {
	    // table probably doesn't exist
	}
	
	StructureTableOptions tableOptions = new StructureTableOptions();
	tableOptions.name = structTableName;

	// Available table types are constants in TableTypeConstants:
	// TABLE_TYPE_MOLECULES, TABLE_TYPE_REACTIONS, 
	// TABLE_TYPE_ANY_STRUCTURES, TABLE_TYPE_MARKUSH_LIBRARIES
	// TABLE_TYPE_QUERY_STRUCTURES
	tableOptions.tableType = tableType;

	// Setting fingerprint parameters according to table type
	tableOptions.fp_numberOfInts =
	    UpdateHandler.FP_DEFAULT_LENGTH_IN_INTS[tableType];
	tableOptions.fp_numberOfOnes =
	    UpdateHandler.FP_DEFAULT_BITS_PER_PATTERN[tableType];
	tableOptions.fp_numberOfEdges =
	    UpdateHandler.FP_DEFAULT_PATTERN_LENGTH[tableType];
	
	UpdateHandler.createStructureTable(connectionHandler, tableOptions);
    }
}