/**
 * Methods for accessing the gene ontology database
 */

import java.util.*;
import java.sql.*;

class GeneOntology {
    Connection con;

    public GeneOntology() {
	try {
	    // Load the MySQL JDBC driver
	    Class.forName("com.mysql.jdbc.Driver");
	} catch (ClassNotFoundException ex) {
	    System.out.println(ex);
	}

	try {
	    // Establish a connection to the MySQL database
	    String host = "dna.csres.utexas.edu";
	    String user = "root";
	    String password = "mobios";
	    String db = "go";
	    con = DriverManager.getConnection("jdbc:mysql://" + host +
		    "/" + db + "?user=" + user + "&password=" + password);

	    // verify the connection is successful by displaying
	    // database software name and version
	    DatabaseMetaData metaData = con.getMetaData();
	    System.out.println("Connected to " +
		    metaData.getDatabaseProductName() + " " +
		    metaData.getDatabaseProductVersion());
	} catch (SQLException ex) {
	    System.err.println(ex);
	}
    }

    /**
     * @param geneSymbol The gene symbol (or name), e.g. 'PROB_ECOLI'
     * @return A list of GO terms associated with this gene ordered
     * with increasing generality. So more general terms appear later
     * in the list. NULL if the symbol is not found.
     * Note: we assume the gene symbol uniquely identifies a gene
     * in the GO database. So we choose the first gene product that
     * matches the given symbol.
     *
     * TODO: fill in the details
     */
    public List getTerms(String geneSymbol) {
	List terms = new ArrayList();

	try {
	    Statement stmt = con.createStatement();

	    // find a gene product that matches the given symbol
	    // TODO: write the query
	    ResultSet rs = stmt.executeQuery();
	    if (!rs.next()) {
		// no gene with this symbol found
		// TODO: print a warning message and return an empty list
	    }

	    // TODO: retrieve the gene product ID
	    int geneID = ;

	    if (rs.next()) {
		// there is another gene product with the same symbol
		// TODO: print a warning message
	    }

	    List goTerms;

	    // look for the GO terms that are directly associated with
	    // this gene product and their parents
	    // TODO: write the query
	    // Hint: the query involves the term table, the graph_path table,
	    // the gene_product table and the association table,
	    // return acc and name (using term table) of all terms that
	    // are parents (using graph_path table) of those terms directly
	    // associated with (using association table) the gene product.
	    // Use the DISTINCT keyword to avoid duplicate terms, e.g.
	    // 'SELECT DISTINCT term...'
	    rs = stmt.executeQuery();

	    while (rs.next()) {
		// TODO: compose a GoTerm object from the query result
		terms.add(new GoTerm());
	    }
	} catch (SQLException ex) {
	    System.err.println(ex);
	}

	return terms;
    }
}
