/**
 * Verification of rosetta relations
 */

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

public class RosettaRelation {
    private Connection con;

    public RosettaRelation() {
	con = Postgres.getConnection("localhost", "rosetta", "cs329e", "");
	if (con == null) {
	    throw new Error("Failed to connect to PostgreSQL server");
	}
    }

    /**
     * Return the number of common GO terms associated with two proteins.
     */
    public int overlapCount(int pID1, int pID2) {
	try {
	    Statement stmt = con.createStatement();
	    // count the number of common terms using an inner join
	    ResultSet rs = stmt.executeQuery("SELECT count(*) " +
		    "FROM t_gofunction f1, t_gofunction f2 " +
		    "WHERE f1.t_protein_id = " + pID1 +
		    " AND f2.t_protein_id = " + pID2 +
		    " AND f1.source = f2.source");
	    rs.next(); // there must be one row
	    return rs.getInt(1);
	} catch (SQLException ex) {
	    throw new Error(ex);
	}
    }

    /**
     * Return the number of common GO terms associated with three proteins.
     */
    public int overlapCount(int pID1, int pID2, int pID3) {
	try {
	    Statement stmt = con.createStatement();
	    // count the number of common terms using an inner join
	    ResultSet rs = stmt.executeQuery("SELECT count(*) " +
		    "FROM t_gofunction f1, t_gofunction f2, " +
		    "t_gofunction f3 " +
		    "WHERE f1.t_protein_id = " + pID1 +
		    " AND f2.t_protein_id = " + pID2 +
		    " AND f3.t_protein_id = " + pID3 +
		    " AND f1.source = f2.source " +
		    "AND f2.source = f3.source");
	    rs.next(); // there must be one row
	    return rs.getInt(1);
	} catch (SQLException ex) {
	    throw new Error(ex);
	}
    }
}
