
package org.fda.multithreading;

import java.io.File;
import java.util.Collection;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.fda.data.Enums.STOPOBJECT;
import org.fda.data.Enums.ScriptRunMode;
import org.fda.data.Utilities;

/**
 *
 * @author Gokhan.Yavas
 */
public class ScriptHelper {
    File[] fArr;
    public ScriptHelper(File[] fA){
        this.fArr = fA;
        for(int k=0; k<fArr.length;k++)
            fArr[k].setExecutable(true);                
    }
    public ScriptHelper(Collection<File> fA){
        this.fArr = fA.toArray(new File[0]);
        for(int k=0; k<fArr.length;k++)
            fArr[k].setExecutable(true);                
    }
    
    public void run(){
        try{
            if(Utilities.submitJobs==ScriptRunMode.qsub || Utilities.submitJobs==ScriptRunMode.sbatch){
                Runtime r = Runtime.getRuntime();
                Process p;
                String qsub_cmd;
                for(int k=0; k< fArr.length; k++){
                    qsub_cmd = Utilities.submitJobs +" "+Utilities.submitJobsParameters+" "+fArr[k].getAbsolutePath();
                    System.out.println(qsub_cmd);
                    p = r.exec(qsub_cmd);            
                    p.waitFor();            
                }
            }
            else{
                BlockingQueue q = new ArrayBlockingQueue(fArr.length+Utilities.no_threads);
                for(int k = 0; k<fArr.length; k++ ){
                    q.put(fArr[k].getAbsolutePath());
                }
                for(int i=0; i<Utilities.no_threads; i++){            
                    q.put(STOPOBJECT.STOP);
                }  
                Thread[] scriptThread = new Thread[Utilities.no_threads];
                // now create the worker threads
                for(int i=0;i<Utilities.no_threads;i++){
                    scriptThread[i] = new Thread(new ScriptRunner(q));
                    scriptThread[i].start();
                }
                for(int i=0; i<scriptThread.length; i++){
                    scriptThread[i].join();
                }                                        
            }
        }
        catch(Exception e){e.printStackTrace();}        
    }    
}
