/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package bicat.GO;

/**
 *
 * @author Hamed
 */
import javax.swing.JOptionPane;
import bicat.gui.BicatGui;
import bicat.run_machine.SwingWorker;
import java.io.File;
import bicat.run_machine.RunMachine;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import  bicat.biclustering.Dataset;
import bicat.util.BicatUtil;
import java.util.Vector;

public class GeneMergeForGO {

    static BicatGui owner;
    public static String GO_ORGANISM="S_cerevisiae";
    public static String GO_BIOLOGICAL_PROCESS="Biological Process";
    public static String GO_MOLECULAR_FUNCTION="Molecular Function";
    public static String GO_CELLULAR_COMPONENT="Cellular Component";
    
    public static String GENE_ASSOCIARION_FILE="S_cerevisiae.BP";
    public static String DESCRIPTION_FILE="GO.BP.use";
    public static String GENE_MERGE_DIRECTORY=owner.currentDirectoryPath+"//genemerge";
    public static String GENE_MERGE_PERL_FILE=owner.currentDirectoryPath+"//genemerge//GeneMerge1.2.pl" ;
    public static String cluster_File_Name="c";
    public static String outputGO_File_Name="GOc";
    //public static String POPULATION_FILE_PATH=owner.POPULATION_FILE_PATH;

    public GeneMergeForGO(BicatGui o) {
		owner = o;
	}
    
public static void createGeneMergeFiles_BiClusteringResults(int datasetIdx,String biclusteringName,LinkedList biclusterList)
    {
      //==== get the association and desc file========================== 
     String organsim=((Dataset)owner.datasetList.get(datasetIdx)).getOrgansim(); // get it from the dataset
     String [] arr=get_GeneAsso_DescFile(organsim,GO_BIOLOGICAL_PROCESS).split(";");
     String geneAsso_File=arr[0];
     String descFile=arr[1];
     
      
        
      String [] clusters_FilePath= export_BiClusters(datasetIdx,biclusteringName,biclusterList);
      String pop_File=owner.currentDirectoryPath+"//"+owner.GO_DIRECTORY_DATASET+datasetIdx+"//pop.txt";
      String output_GoPath=owner.currentDirectoryPath+"//"+owner.GO_DIRECTORY_DATASET+datasetIdx+"//"+biclusteringName+"//"+outputGO_File_Name;
      
      bicat.biclustering.Bicluster bc;
      String fullOutputPath="";
      for(int i=0;i<biclusterList.size();i++)
      {
          bc = (bicat.biclustering.Bicluster) biclusterList.get(i);
          fullOutputPath=output_GoPath+bc.getId()+".txt";
          //fullOutputPath="./"+owner.GO_DIRECTORY_DATASET+datasetIdx+"/"+biclusteringName+"/"+outputGoFileName+i+".txt";
          //call the function that generate the files.
          // createGeneMergeFile(populationPath,clusterFilePathes[i],fullOutputPath);          
          createGeneMergeFile(geneAsso_File,descFile,pop_File,clusters_FilePath[i],fullOutputPath);                    
      }
     
      JOptionPane.showMessageDialog(null, "Bi/Clustering Calculations finished.\nPlease wait till the GeneOntology calculations finished. \nresults can be found in the bicluster results section of the current dataset.");
      /* show message confirms that it si finished,may be u need the delay 
       */
     
    }
  
public static  String [] export_BiClusters  (int datasetIdx,String biclusteringName,LinkedList biclusterList)
{
   String [] filenames=new String [ biclusterList.size()];
   String exportedClusters_Path=owner.currentDirectoryPath+"//"+owner.GO_DIRECTORY_DATASET+datasetIdx+"//"+biclusteringName;
   try {
   
       // Create one directory to save the cluster files
       boolean success = (new File(exportedClusters_Path)).exists();
        if (! success) 
        {
          success= (new File(exportedClusters_Path)).mkdirs();
          System.out.println("Directories: "+exportedClusters_Path+ " created");
        }  

       
       bicat.biclustering.Bicluster bc;
       FileWriter fw=null;
       for (int i = 0; i < biclusterList.size(); i++) 
             {

                    bc = (bicat.biclustering.Bicluster) biclusterList.get(i);
                    fw = new FileWriter(exportedClusters_Path+"//"+cluster_File_Name+bc.getId()+".txt",false);
                    // write genes to file
                    for (int j = 0; j < bc.gd; j++){
                            fw.write(owner.currentDataset.getGeneName(bc.genes[j]));// pre.getGeneName(bc.genes[j]) + " ";
                            fw.write('\n');
                    }
                    fw.close();
                    filenames[i]=exportedClusters_Path+"//"+cluster_File_Name+bc.getId()+".txt";
              }
  
     
      } catch (IOException ioe) {
          
        JOptionPane.showMessageDialog(owner, " Error : cannot access the GO working directory.. close the opened Files");  
        System.err.println(ioe);
        ioe.printStackTrace();
        } 

return filenames;
}
   
 public static String get_GeneAsso_DescFile(String organism,String GoType)
{
     String geneAsso=organism;
     String prefix="";
     
     if(GO_BIOLOGICAL_PROCESS.equalsIgnoreCase(GoType))
            prefix=".BP";    
     if(GO_MOLECULAR_FUNCTION.equalsIgnoreCase(GoType))
            prefix=".MF";         
     if(GO_CELLULAR_COMPONENT.equalsIgnoreCase(GoType))
            prefix=".CC";
      
     geneAsso=geneAsso+prefix;
     String descFile="GO"+prefix+".use";
     
     return geneAsso+";"+descFile;             
}   

 
 public static void createGeneMergeFiles_GOAnalysis( int datasetIdx,String GOType,String pop_File,String biclusteringName,LinkedList biclusterList)
    {
     //==== get the association and desc file========================== 
     String organsim=((Dataset)owner.datasetList.get(datasetIdx)).getOrgansim(); // get it from the dataset
     String [] arr=get_GeneAsso_DescFile(organsim,GOType).split(";");
     String geneAsso_File=arr[0];
     String descFile=arr[1];
     
     //============== get the cluster file path
     bicat.biclustering.Bicluster bc;
     String clusters_FilePath[]=new String [ biclusterList.size()];
     String exportedClusters_Path=owner.currentDirectoryPath+"//"+owner.GO_DIRECTORY_DATASET+datasetIdx+"//"+biclusteringName;
     for(int i=0;i<clusters_FilePath.length;i++)
     {
         bc = (bicat.biclustering.Bicluster) biclusterList.get(i);
         clusters_FilePath[i]=exportedClusters_Path+"//"+cluster_File_Name+bc.getId()+".txt";
     }
     //================== get the outputpath
     String output_GoPath=owner.currentDirectoryPath+"//"+owner.GO_DIRECTORY_DATASET+datasetIdx+"//"+biclusteringName+"//"+outputGO_File_Name;
     String fullOutputPath="";
      for(int i=0;i<biclusterList.size();i++)
      {
          bc = (bicat.biclustering.Bicluster) biclusterList.get(i);
          fullOutputPath=output_GoPath+bc.getId()+".txt";
          //call the function that generate the files.
          createGeneMergeFile(geneAsso_File,descFile,pop_File,clusters_FilePath[i],fullOutputPath);          
      }
     
      JOptionPane.showMessageDialog(null, "Please wait till the GeneOntology calculations finished. \nresults can be found in the bicluster results section of the current dataset.");
      /* show message confirms that it si finished,may be u need the delay 
       */
     
    }


 public static void createGeneMergeFiles_GoComapare_extLists( Vector externalLists,String goType)
    {
     String go_FolderPath=owner.currentDirectoryPath+"//"+owner.GO_DIRECTORY_DATASET_EXTERNAL;
     List list=null;
     String [] go_FilePaths=null;
     for(int i=0;i<externalLists.size();i++)
     {
         list=(List)externalLists.get(i);
        //if(list.getGoFilePaths()==null || list.getGoFolderPath()==null || list.getGoFolderPath().equalsIgnoreCase(" ") || list.getGoFolderPath().equalsIgnoreCase(""))
         if(list.getGoFilePaths()==null)
         {
             go_FilePaths=new String[list.getClusterFilePaths().length];
             //=======create the directory of the bilcuster name;
             createDirectory(go_FolderPath+"//"+list.getName());

             //==== get the association and desc file========================== 
             String [] arr=get_GeneAsso_DescFile(BicatUtil.mapOrgansimName(list.getOrganism()),goType).split(";");
             String geneAsso_File=arr[0];
             String descFile=arr[1];

             //================== create the gene merge files and save  the output paths
             for(int j=0;j<list.getClusterFilePaths().length;j++)
              {
                  go_FilePaths[j]=go_FolderPath+"//"+list.getName()+"//"+outputGO_File_Name+j+".txt";
                  //call the function that generate the files.
                  createGeneMergeFile(geneAsso_File,descFile,list.getPop_Path(),list.getClusterFilePaths()[j],go_FilePaths[j]);          
              }

              list.setGoFilePaths(go_FilePaths);

              /* show message confirms that it si finished,may be u need the delay 
               */
           }
     }
      JOptionPane.showMessageDialog(null, "Please wait till the GeneOntology calculations finished. \nresults can be found in the Comparison view.");
   }

 public static boolean createDirectory(String dir)
 {
      // Create one directory to save the go files for the ext lists. 
     boolean success =false;
     try {
        success=(new File(dir)).exists();
        if (! success) 
        {
          success= (new File(dir)).mkdirs();
          System.out.println("Directories: "+dir+ " is created");
        }  
       } catch (Exception ioe) {
          
        JOptionPane.showMessageDialog(owner, " Error : cannot access the GO working directory..Please close the opened Files");  
        System.err.println(ioe);
        ioe.printStackTrace();
        } 
     
     return success;
     
 }
         //public static void createGeneMergeFile(String pop_FilePath,String study_Filepath,String output_FilePath)
//{
//    Process proc=null;
//            try { 
//             
//            proc= Runtime.getRuntime().exec(new String [] {GENE_MERGE_DIRECTORY+"//"+"getGeneMerge.exe",GENE_ASSOCIARION_FILE,DESCRIPTION_FILE,pop_FilePath,study_Filepath,output_FilePath},null,new File(GENE_MERGE_DIRECTORY));    
//               }catch(Exception ex)
//            {
//                ex.printStackTrace();
//            }
//         
//            System.out.println("GeneMerge  is running here in the method..."); 
// }

public static void createGeneMergeFile(String asscociationFile,String desc_File,String pop_FilePath,String study_Filepath,String output_FilePath)
{
    Process proc=null;
            try { 
             
            proc= Runtime.getRuntime().exec(new String [] {GENE_MERGE_DIRECTORY+"//"+"getGeneMerge.exe",asscociationFile,desc_File,pop_FilePath,study_Filepath,output_FilePath},null,new File(GENE_MERGE_DIRECTORY));    
               }catch(Exception ex)
            {
                ex.printStackTrace();
                
            }
         
            System.out.println("GeneMerge  is running here in the method..."); 
 }

}
