package de.ugoe.cs.eventbench.commands;

import java.security.InvalidParameterException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

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

public class CMDgenerateRandomSequences implements Command {

	@Override
	public void run(List<Object> parameters) {
		String modelname;
		String sequencesName;
		int numSessions;
		long maxIter;
		int minLength = 0;
		int maxLength = Integer.MAX_VALUE;
		try {
			modelname = (String) parameters.get(0);
			sequencesName = (String) parameters.get(1);
			numSessions = Integer.parseInt((String) parameters.get(2));
			maxIter = numSessions*10;
			if( parameters.size()>=4 ) {
				maxIter = Long.parseLong((String) parameters.get(3));
			}
			if( parameters.size()>=5 ) {
				minLength = Integer.parseInt((String) parameters.get(4));
			}
			if( parameters.size()>=6 ) {
				maxLength = Integer.parseInt((String) parameters.get(5));
			}
		}
		catch (Exception e) {
			throw new InvalidParameterException();
		}
		
		IStochasticProcess model = null; 
		Object dataObject = GlobalDataContainer.getInstance().getData(modelname);
		if( dataObject==null ) {
			Console.println("Model " + modelname + " not found in storage.");
		}
		else if( !(dataObject instanceof IStochasticProcess) ) {
			Console.println("Object " + modelname + " not of type MarkovModel!");
		} else {
			model = (IStochasticProcess) dataObject;
			Set<List<? extends Event<?>>> sequences = new HashSet<List<? extends Event<?>>>(numSessions);
			long numIterations = 0;
			while( sequences.size()<numSessions && numIterations<maxIter ) {
				List<? extends Event<?>> generatedSequence = model.randomSequence();
				if( generatedSequence.size()>=minLength && generatedSequence.size()<=maxLength ) {
					sequences.add(generatedSequence);
				}
				numIterations++;
			}
			if( sequences.size() < numSessions ) {
				Console.println("Only " + sequences.size() + " unique sessions generated after " + maxIter + " iterations");
			}
			if( GlobalDataContainer.getInstance().addData(sequencesName, sequences) ) {
				Console.traceln("Old data \"" + sequencesName + "\" overwritten");
			}
		}
	}

	@Override
	public void help() {
		Console.println("Usage: generateRandomSequenecs <modelName> <sequencesName> <numSessions> {<maxIter> <minLength> <maxLength>}");
	}

}
