package de.ugoe.cs.eventbench.jfc.commands;

import java.io.File;
import java.security.InvalidParameterException;
import java.util.Collection;
import java.util.List;

import de.ugoe.cs.eventbench.CommandHelpers;
import de.ugoe.cs.eventbench.data.GlobalDataContainer;
import de.ugoe.cs.eventbench.jfc.JFCLogParser;
import de.ugoe.cs.eventbench.jfc.data.JFCEvent;
import de.ugoe.cs.eventbench.jfc.data.JFCTargetComparator;
import de.ugoe.cs.util.console.Command;
import de.ugoe.cs.util.console.Console;

/**
 * <p>
 * Command that tries to parse all files in a folder as if they were log files
 * generated by the JFCMonitor. The result is one set of sequences for all files
 * (not one set of sequences for each file!).
 * </p>
 * 
 * @author Steffen Herbold
 * @version 1.0
 */
public class CMDparseDirJFC implements Command {

	/*
	 * (non-Javadoc)
	 * 
	 * @see de.ugoe.cs.util.console.Command#run(java.util.List)
	 */
	@Override
	public void run(List<Object> parameters) {
		String path;
		String sequencesName = "sequences";

		try {
			path = (String) parameters.get(0);
			if (parameters.size() >= 2) {
				sequencesName = (String) parameters.get(1);
			}
		} catch (Exception e) {
			throw new InvalidParameterException();
		}

		File folder = new File(path);
		if (!folder.isDirectory()) {
			Console.printerrln(path + " is not a directory");
			return;
		}

		JFCTargetComparator.setMutable(true);
		JFCLogParser parser = new JFCLogParser();

		String absolutPath = folder.getAbsolutePath();
		for (String filename : folder.list()) {
			String source = absolutPath + "/" + filename;
			Console.traceln("Processing file: " + source);

			parser.parseFile(source);
		}

		Collection<List<JFCEvent>> sequences = parser.getSequences();
		Console.traceln("Pre-computing event target equalities.");
		// compare all Events to a dummy event to make sure they are known by
		// the JFCTargetComparator
		JFCEvent dummyEvent = new JFCEvent("dummy");
		for (List<JFCEvent> sequence : sequences) {
			for (JFCEvent event : sequence) {
				event.equals(dummyEvent);
			}
		}
		JFCTargetComparator.setMutable(false);

		if (GlobalDataContainer.getInstance().addData(sequencesName, sequences)) {
			CommandHelpers.dataOverwritten(sequencesName);
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see de.ugoe.cs.util.console.Command#help()
	 */
	@Override
	public void help() {
		Console.println("Usage: parseDirJFC <path> {<sequencesName>}");
	}

}
