package pp2.datahandler.blast;

import java.io.*;
import java.util.*;

public class BlastPerformer {

	private File database;
	private String formatdbPath = "formatdb";
	private String blastPath = "blastpgp";

	public BlastPerformer(File database) {
		this.database = database;
	}
	
	public BlastPerformer(String database) {
		this.database = new File(database);
	}
	
	public Process startBLAST(File queryfile, String[] parameters) throws IOException, InterruptedException {

			//check if database is already formatted
			if(!databaseReady()) {
				
				//format database using formatdb
				String format  = formatdbPath+" -i "+database;
				Runtime rt1    = java.lang.Runtime.getRuntime();
				Process proc1  = rt1.exec(format);
				int exitVal1   = proc1.waitFor();
				System.err.println("Formatdb exit value: "+exitVal1);
			}
			
			StringBuffer param = new StringBuffer();
			for(String p : parameters) {
				param.append(p+" ");
			}
			
			//start the BLAST command
			String command = blastPath+" "+param+"-d "+database.getAbsolutePath()+" -i "+queryfile.getAbsolutePath();
			Runtime rt   = java.lang.Runtime.getRuntime();
			Process proc = rt.exec(command);
			
			

			return proc;
	}
	
	/**
	 * Checks if database is already formatted
	 * @return TRUE if database is formatted
	 */
	private boolean databaseReady() {
		File directory = database.getParentFile();
    	String stem    = database.getName();
		String[] files = directory.list();
		List<String> names = Arrays.asList(files);
		//check if all files generated by formatdb are available
		if(names.contains(stem+".phr") 
				&& names.contains(stem+".pin") 
				&& names.contains(stem+".psq")) {
			System.err.println("Database is already formatted.");
			return true;
		} else {
			return false;
		}
	}

	
	public void setBlastPath(String blastPath) {
		this.blastPath = blastPath;
	}
	
	public void setFormatdbPath(String formatdbPath) {
		this.formatdbPath = formatdbPath;
	}

}
