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

public class Milestone2
{
	private Connection conn; 

	public Milestone2()
	{
		//TO BE CHANGED  for your Postgres setting
		conn = Postgres.getConnection("localhost", "db_name", "user_name", "password");
	}

	public Milestone2(String hostaddress, String dbname, String usr_name, String pass)
	{
		conn = Postgres.getConnection(hostaddress, dbname, usr_name, pass);
	}
	public void begin()
	{
	   try{
		Statement stmt = conn.createStatement();
		// 1. open connection to retireve protien from database
		//    store sequence and its id  in a String List and id List;
		ResultSet rs = stmt.executeQuery(
                	"SELECT T_Protein_ID, sequence FROM T_Protein");
		List idList = new ArrayList();
		List seqs = new ArrayList();
        	while (rs.next()) {
			seqs.add(rs.getString("sequence"));
			idList.add(new Integer(rs.getInt("t_protein_id")));
		}
		
		// 2. For each pair of protein, 
		SmithWaterman sw =null;
		List matches = null;
		for (int i=0; i< seqs.size(); i++)
		{
		   String seqA = (String) seqs.get(i);
		   int idA = ((Integer) idList.get(i)).intValue();
		   for (int j=i+1; j< seqs.size(); j++)
		   {

		      //    2a. compute local alignment
		      String seqB = (String) seqs.get(j);
		      int idB = ((Integer) idList.get(j)).intValue();
		      sw = new SmithWaterman(seqA, seqB);

		      //    2b. store the set of hsp as a list;
		      matches = SimpleChaining.chaining(sw.getMatches(), false);
		      	
		      //    2c. insert each list of matches in to match table
                      double sum =0; 
		      for (ListIterator iter = matches.listIterator(); iter.hasNext();)
		      {
			SimpleChaining.Match m = (SimpleChaining.Match) iter.next();
			stmt.executeUpdate( "INSERT INTO T_Match"
			 + " (fromA, fromB, toA, toB, score, t_protein_id, t_protein_t_protein_id) "
			 + " VALUES ( " +  m.getFromA() +", " +  m.getFromB() +", "+  m.getToA() +", "
			 +  m.getToB() +", " +  m.getScore() +", " + idA +", "+ idB +" ) ");
		         sum+=m.getScore();
		      }
		     
		      //    2d. insert final score into local alignment table;
                      stmt.executeUpdate(" INSERT INTO T_LocalAlignment "
                            + "(totalScore, t_protein_id, t_protein_t_protein_id) "
			    + " VALUES ( "+ sum +", "+ idA +", " + idB +" ) ");                                
		   }
	    	}
            } catch (Exception e)
            {
		System.out.println("Exception caught ");
		e.printStackTrace();
	    }
	}

	public static void main(String [] args)
	{
		
		Milestone2 ms2 = new Milestone2();
		ms2.begin();
	}
	
} 

