package de.ugoe.cs.util.console.defaultcommands;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.List;

import de.ugoe.cs.util.console.Command;
import de.ugoe.cs.util.console.CommandExecuter;
import de.ugoe.cs.util.console.Console;

/**
 * <p>
 * Implements a command to execute batchs of {@link Command}s, defined by batch
 * file, to allow scripted executions.
 * </p>
 * 
 * @author Steffen Herbold
 */
public class CMDexec implements Command {

	/**
	 * <p>
	 * Executes a batch of {@link Command}s that are listed line by line in the
	 * given file.
	 * </p>
	 * <p>
	 * Usage: <code>exec filename</code>
	 * </p>
	 * 
	 * @see de.ugoe.cs.util.console.commands.Command#run(java.util.List)
	 */
	public void run(List<Object> parameters) {
		String script;
		try {
			script = (String) parameters.get(0);
		} catch (Exception e) {
			throw new InvalidParameterException();
		}
		try {
			String[] commands;
			File f = new File(script);
			FileReader reader = new FileReader(f);
			char[] buffer = new char[(int) f.length()];
			reader.read(buffer);
			commands = (new String(buffer)).split("\n");
			for (String command : commands) {
				Console.println(command);
				CommandExecuter.getInstance().exec(command);
			}
			reader.close();
		} catch (FileNotFoundException e) {
			Console.printerrln(e.getMessage());
		} catch (IOException e) {
			Console.printerrln(e.getMessage());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see databasebuilder.console.commands.Command#help()
	 */
	@Override
	public void help() {
		Console.println("Usage: exec filename");
	}
}
