package geneFinder;

/**
 * call BWA to map the rna reads against the reference genome 
 * Copyright (c) 2013,
 * Franziska Zickmann, 
 * ZickmannF@rki.de, Robert Koch-Institute, Berlin, Germany
 * Distributed under the GNU Lesser General Public License, version 3.0
 */


import java.io.File;
import java.io.IOException;


public class BWA_Call {
	
	/*
	 * map the reads against all ORFs using bwa 
	 * creates a sam output file
	 * note: allows only one setting for the indexing (-a XX) and various ones in the aln step
	 */

	public void callBWA(File refFile, String nameOutSamFile) {

		File rnaFile = null;

		if(GeneFinder.rnaFilesWithNames.keySet().size() > 1){

			// more than one read file, so concatenate them to one big file

			rnaFile = new File(GeneFinder.pathOut+"mergedReadFiles.fastq");
			callConcatenateReadFiles(); // perform the concatenation

		}else{
			for(File readFile : GeneFinder.rnaFilesWithNames.keySet()){
				rnaFile = readFile;
			}
		}

		// now that we have the read file, do the alignment 

		System.out.println("Start to do the alignment with BWA...");			
		WriteOutput.writeToLogFile("Start to do the alignment with BWA... \n");

		long timebef = System.currentTimeMillis();
		long timeAfter = 0;


		String nameIndexTool = "is";	// these are the variables for the different options given for each part of the BWA process
		String optionString_aln = "";
		String optionString_samse = "";

		if(GeneFinder.settingMapper != null){	
			String[] returnArr = getMapperOptions_BWA(nameIndexTool,optionString_aln,optionString_samse);  // get the options
			nameIndexTool = returnArr[0];
			optionString_aln = returnArr[1];
			optionString_samse = returnArr[2];
		}else{
			optionString_aln = "0";   // "0" is the indicator that no options are provided
			optionString_samse = "0";
		}

		System.out.print("Indexing.... ");	// first step
		String firstExe = "python " + GeneFinder.pathToHelpFiles+"bwa_index.py " + refFile + " " + nameIndexTool;    // first index reference file		
		Giira.callAndHandleOutput(firstExe,true);

		System.out.println("\nPerform alignment.... ");

		if(!GeneFinder.useBWAsw){
			String saiOut = GeneFinder.pathOut+"aln_sa.sai";

			String secondExe = "python "+GeneFinder.pathToHelpFiles+"bwa_aln.py " + optionString_aln + " " + refFile + " " + rnaFile + " " + saiOut;  // perform alignment				
			Giira.callAndHandleOutput(secondExe,true);

			System.out.println("\nWrite to SAM format....");

			String thirdExe = "python "+GeneFinder.pathToHelpFiles+"bwa_samse.py " + optionString_samse + " " + refFile + " " + saiOut + " " + rnaFile + " " + nameOutSamFile;  //output: sam file
			Giira.callAndHandleOutput(thirdExe,true);

		}else{
			String secondExe = "python "+GeneFinder.pathToHelpFiles+"bwa_sw.py " + optionString_samse + " " + refFile +  " " + rnaFile + " " + nameOutSamFile;  //output: sam file
			Giira.callAndHandleOutput(secondExe,true);
		}

		System.out.println("\nDone.");
		timeAfter = System.currentTimeMillis();	    
		System.out.println("Time required for the alignment: "+ (double) (timeAfter-timebef)/1000.0 +"s.");
		WriteOutput.writeToLogFile(" Done.\n Time required for the alignment: "+ (double) (timeAfter-timebef)/1000.0 +"s.\n");



	}
	
	/*
	 * if more than one read file is provided, concatenate them for BWA to provide one big merged read file
	 */
	
	public static void callConcatenateReadFiles(){
		
		System.out.println("Concatenate read files.");
		Runtime prepRef = Runtime.getRuntime();
		Process firstExe;
		
		String allRnaNames = new String();  // necessary for python helper script
		
		for(File rnaFileTemp : GeneFinder.rnaFilesWithNames.keySet()){  // generate the name
			String name = GeneFinder.rnaFilesWithNames.get(rnaFileTemp);
			allRnaNames += name+"&&";
		}

		try { // call python helper script
			String exe = "python "+GeneFinder.pathToHelpFiles+"callCat_RnaFile.py " + allRnaNames + " " + GeneFinder.pathOut+"mergedReadFiles.fastq";
			firstExe = prepRef.exec(exe);
			firstExe.waitFor();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * if options are provided by the user, extract those options
	 */
	
	public static String[] getMapperOptions_BWA(String nameIndexTool, String optionString_aln, String optionString_samse){
		
		String[] splitParts = GeneFinder.settingMapper.split("_");
		for(int i=0;i<splitParts.length;i++){  // each part is for one of the parts of BWA (indexing, aln, samse)
			String[] paraSplit = splitParts[i].split(",");
			for(String para : paraSplit){
				if(i==0){
					String[] paraArr = para.split("=");
					nameIndexTool = paraArr[1];
				}else if(i==1){		// aln part, add option here
					String[] paraArr = para.split("=");
					if(paraArr.length == 1){	// this means an option that only consists of one tag
						optionString_aln = optionString_aln+paraArr[0]+"_";
					} else{
						optionString_aln = optionString_aln+paraArr[0]+"_"+paraArr[1]+"_";
					}
				}else{ // samse part, add option here
					String[] paraArr = para.split("=");
					if(paraArr.length == 1){	// this means an option that only consists of one tag
						optionString_samse = optionString_samse+paraArr[0]+"_";
					} else{
						optionString_samse = optionString_samse+paraArr[0]+"_"+paraArr[1]+"_";
					}
				}
			}

		}

		// now prepare the option string in a way that it can be passed to the python helper script
		
		if(splitParts[1].length() > 1){
			optionString_aln="["+optionString_aln.substring(0, (optionString_aln.length()-1))+"]";
		}
		if(splitParts[2].length() > 1){
			optionString_samse="["+optionString_samse.substring(0, (optionString_samse.length()-1))+"]";
		}
		
		return new String[] {nameIndexTool,optionString_aln,optionString_samse};
	}
	
}
