package de.ugoe.cs.eventbench.commands;

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

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

/**
 * <p>
 * Abstract class for commands to train {@link TrieBasedModel}s.
 * </p>
 * 
 * @author Steffen Herbold
 * @version 1.0
 */
public abstract class AbstractTrainCommand implements Command {

	/**
	 * <p>
	 * Handling of additional parameters.
	 * </p>
	 * 
	 * @param parameters
	 *            same as the parameters passed to {@link #run(List)}.
	 * @throws Exception
	 *             thrown, if there is an error parsing the parameters
	 */
	abstract void handleAdditionalParameters(List<Object> parameters)
			throws Exception;

	/**
	 * <p>
	 * Returns a concrete instance of {@link TrieBasedModel} to be trained. This
	 * is a factory method.
	 * </p>
	 * 
	 * @return instance of {@link TrieBasedModel}
	 */
	abstract TrieBasedModel createModel();

	/**
	 * <p>
	 * The command is implemented as a template method. The general structure of
	 * the command is always the same, only the parameters of the command and
	 * the creation of the {@link TrieBasedModel} instance. The former is
	 * handled by {@link #handleOptionalParameters(List)}, the latter by
	 * {@link #createModel()}.
	 * </p>
	 * 
	 * @see de.ugoe.cs.util.console.Command#run(java.util.List)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void run(List<Object> parameters) {
		String modelname;
		String sequencesName;

		try {
			modelname = (String) parameters.get(0);
			sequencesName = (String) parameters.get(1);
			handleAdditionalParameters(parameters);
		} catch (Exception e) {
			throw new InvalidParameterException();
		}

		Collection<List<Event<?>>> sequences = null;
		Object dataObject = GlobalDataContainer.getInstance().getData(
				sequencesName);
		if (dataObject == null) {
			Console.println("Object " + sequencesName
					+ " not found in storage.");
			return;
		}
		try {
			sequences = (Collection<List<Event<?>>>) dataObject;
		} catch (ClassCastException e) {
			Console.println("Object " + sequencesName
					+ "not of type Collection<List<Event<?>>>.");
			return;
		}
		/* TODO implement better type check
		if (sequences.size() == 0 || !(sequences.get(0).get(0) instanceof Event) ) {
			Console.println("Object " + sequencesName
					+ "not of type Collection<List<Event<?>>>.");
			return;
		}
		*/

		TrieBasedModel model = createModel();
		model.train(sequences);
		if (GlobalDataContainer.getInstance().addData(modelname,
				model)) {
			Console.traceln("Old data \"" + modelname
					+ "\" overwritten");
		}
		
	}

}
