package de.ugoe.cs.eventbench.jfcmonitor;

import java.awt.AWTEvent;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;

/**
 * <p>
 * Start-up class of the application.
 * </p>
 * <p>
 * Launches the application under test in the same JVM.
 * </p>
 * 
 * @author Steffen Herbold
 * @version 1.0
 */
public class Runner {

	/**
	 * <p>
	 * Debugging variable. If set to true, the logging is also written to the
	 * console.
	 * </p>
	 */
	private final static boolean stdOutputWrite = true;

	/**
	 * <p>
	 * Main method of the application.
	 * </p>
	 * 
	 * @param args
	 *            the first parameter defines the Jar file that contains the
	 *            start-up information of the application under test. The
	 *            remaining parameters are passed on the toe application under
	 *            test.
	 */
	public static void main(String[] args) {
		String logfileName = "jfcmonitor_" + System.currentTimeMillis()
				+ ".log";

		FileOutputStream fis;
		OutputStreamWriter writer;
		try {
			// the writer is not closed explicitly!
			fis = new FileOutputStream(logfileName, true);
			writer = new OutputStreamWriter(fis, "UTF-16");
		} catch (IOException e) {
			System.err.println("JFCMONITOR -- failure opening logfile: "
					+ e.getMessage());
			return;
		}

		AWTEventListener listenerFile = new JFCListener(writer);
		Toolkit.getDefaultToolkit().addAWTEventListener(listenerFile,
				AWTEvent.KEY_EVENT_MASK);
		Toolkit.getDefaultToolkit().addAWTEventListener(listenerFile,
				AWTEvent.MOUSE_EVENT_MASK);

		if (stdOutputWrite) {
			AWTEventListener listenerStdOut = new JFCListener(
					new OutputStreamWriter(System.out));
			Toolkit.getDefaultToolkit().addAWTEventListener(listenerStdOut,
					AWTEvent.KEY_EVENT_MASK);
			Toolkit.getDefaultToolkit().addAWTEventListener(listenerStdOut,
					AWTEvent.MOUSE_EVENT_MASK);
		}

		JarLauncher launcher = new JarLauncher(args[0], Arrays.copyOfRange(
				args, 1, args.length));
		launcher.exec();
	}
}
