package de.ugoe.cs.quest.commands.usage;

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

import de.ugoe.cs.quest.CommandHelpers;
import de.ugoe.cs.quest.SequenceInstanceOf;
import de.ugoe.cs.quest.eventcore.Event;
import de.ugoe.cs.quest.usageprofiles.TrieBasedModel;
import de.ugoe.cs.util.console.Command;
import de.ugoe.cs.util.console.GlobalDataContainer;

/**
 * <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 #handleAdditionalParameters(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();
		}

		Object dataObject = GlobalDataContainer.getInstance().getData(
				sequencesName);
		if (dataObject == null) {
			CommandHelpers.objectNotFoundMessage(sequencesName);
			return;
		}
		if (!SequenceInstanceOf.isCollectionOfSequences(dataObject)) {
			CommandHelpers.objectNotType(sequencesName,
					"Collection<List<Event<?>>>");
			return;
		}
		Collection<List<Event>> sequences = (Collection<List<Event>>) dataObject;

		TrieBasedModel model = createModel();
		model.train(sequences);
		if (GlobalDataContainer.getInstance().addData(modelname, model)) {
			CommandHelpers.dataOverwritten(modelname);
		}

	}

}
