package org.inria.bmajwatcher.server.launcher;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;

/**
 * Launcher that runs commands on localhost.
 * 
 * @author rsabas
 *
 */
public class LocalLauncher implements Launcher {
	
	private String biomajRoot = null;
	
	private Logger log = Logger.getLogger(LocalLauncher.class);
	
	
	/**
	 * LocalLauncher should only be created via LauncherFactory as only
	 * on localLauncher is kept for the application.
	 * 
	 * @param context
	 */
	protected LocalLauncher(ServletContext context) {
		biomajRoot = context.getInitParameter("BIOMAJ_ROOT");
	}
	
	@Override
	public boolean startUpdate(String bankName) {
		String command = "bash " + biomajRoot + "/bin/biomaj.sh --update " + bankName;
		return executeCommand(command);
	}

	@Override
	public boolean startUpdateFromScratch(String bankName) {
		String command = "bash " + biomajRoot + "/bin/biomaj.sh --update " + bankName + " --fromscratch";
		return executeCommand(command);
	}

	@Override
	public boolean stopUpdate(String bankName) {
		String cmd = "";
		return executeCommand(cmd);
	}
	
	@Override
	public boolean rebuild(String bankName) {
		String command = "bash " + biomajRoot + "/bin/biomaj.sh --rebuild " + bankName;
		return executeCommand(command);
	}

	@Override
	public boolean startUpdateNew(String bankName) {
		String command = "bash " + biomajRoot + "/bin/biomaj.sh --update " + bankName + " --new";
		return executeCommand(command);
	}
	
	@Override
	public boolean removeAll(String bankName, boolean noHistory, boolean keepProd) {
		String command = "";
		if (noHistory) {
			command = "bash " + biomajRoot + "/bin/biomaj.sh --remove " + bankName + " --all-no-history";
		} else {
			command = "bash " + biomajRoot + "/bin/biomaj.sh --remove " + bankName + " --all";
		}
		

		if (keepProd)
			command += " --keep-dir-prod";
		
		return executeCommand(command);
	}
	
	@Override
	public boolean removeDirs(List<String> paths, String bankName, boolean keepProd) {
		String command = "bash " + biomajRoot + "/bin/biomaj.sh --remove " + bankName + " --paths";
		
		for (String path : paths)
			command += " " + path;
		
		if (keepProd)
			command += " --keep-dir-prod";
		
		return executeCommand(command);
	}
	
	
	private boolean executeCommand(String cmd) {
		log.info("LocalLauncher::Command : " + cmd);
		try {	
			Runtime.getRuntime().exec(cmd);
			/*
			Process p = Runtime.getRuntime().exec(cmd);
			
			BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String line = "";
			while ( (line = br.readLine()) != null) {
				System.out.println(line);
			}
			br.close();*/
//			process.waitFor();
		} catch (IOException ex) {
			log.error("Command error : " + ex);
			return false;
		}
		return true;
	}

}
