package de.ugoe.cs.eventbench.commands;

import java.security.InvalidParameterException;
import java.util.List;
import java.util.Random;

import de.ugoe.cs.eventbench.data.Event;
import de.ugoe.cs.eventbench.data.GlobalDataContainer;
import de.ugoe.cs.eventbench.models.PredictionByPartialMatch;
import de.ugoe.cs.util.console.Command;
import de.ugoe.cs.util.console.Console;

/**
 * <p>
 * Command that trains Prediction by Partial Match (PPM) models.
 * </p>
 * 
 * @author Steffen Herbold
 * @version 1.0
 */
public class CMDtrainPPM implements Command {

	/*
	 * (non-Javadoc)
	 * 
	 * @see de.ugoe.cs.util.console.Command#help()
	 */
	@Override
	public void help() {
		Console.println("Usage: trainPPM <modelName> <probEscape> <maxOrder> {<minOrder>}");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see de.ugoe.cs.util.console.Command#run(java.util.List)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void run(List<Object> parameters) {
		String modelname;
		double probEscape;
		int maxOrder;
		int minOrder = 0;
		try {
			modelname = (String) parameters.get(0);
			probEscape = Double.parseDouble((String) parameters.get(1));
			maxOrder = Integer.parseInt((String) parameters.get(2));
			if (parameters.size() == 4) {
				minOrder = Integer.parseInt((String) parameters.get(3));
			}
		} catch (Exception e) {
			throw new InvalidParameterException();
		}

		List<List<Event<?>>> sequences = null;
		Object dataObject = GlobalDataContainer.getInstance().getData(
				"sequences");

		try {
			sequences = (List<List<Event<?>>>) dataObject;
			if (sequences.size() > 0) {
				if (sequences.get(0).get(0) instanceof Event) {
					PredictionByPartialMatch model = new PredictionByPartialMatch(
							maxOrder, minOrder, new Random(), probEscape);
					model.train(sequences);
					if (GlobalDataContainer.getInstance().addData(modelname,
							model)) {
						Console.traceln("Old data \"" + modelname
								+ "\" overwritten");
					}
				} else {
					Console.traceln("Illegal use of \"sequences\" parameter in the GlobalDataContainer.");
					Console.traceln("The parameter should always be of type List<List<Event>>!");
				}
			}
		} catch (ClassCastException e) {
			Console.println("Sequences need to be loaded first using parseXML");
		}
	}

}
