package de.ugoe.cs.util.console.defaultcommands;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
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>
 * Command to execute a batch of {@link Command}s. The batch is defined as a
 * text file, where each line defines one command.
 * </p>
 * 
 * @author Steffen Herbold
 * @version 1.0
 */
public class CMDexec implements Command {

	/*
	 * (non-Javadoc)
	 * 
	 * @see de.ugoe.cs.util.console.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);
			FileInputStream fis = new FileInputStream(f);
			InputStreamReader reader = new InputStreamReader(fis, "UTF-8");
			char[] buffer = new char[(int) f.length()];
			reader.read(buffer);
			commands = (new String(buffer)).split("\n");
			for (String command : commands) {
				Console.traceln(command.trim());
				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>");
	}
}
