//   Copyright 2012 Georg-August-Universität Göttingen, Germany
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

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.util.List;
import java.util.logging.Level;

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 IllegalArgumentException();
		}
		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) {
			    if( !command.trim().startsWith("%")) {
				Console.traceln(Level.INFO, "Executing \"" + 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 String help() {
		return "exec <filename>";
	}
}
