package de.ugoe.cs.eventbench.commands;

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

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

public class CMDcalcCoverage implements Command {

	@SuppressWarnings("unchecked")
	@Override
	public void run(List<Object> parameters) {
		String modelname;
		String[] sequenceNames;
		int minLength;
		int maxLength;
		try {
			modelname = (String) parameters.get(0);
			sequenceNames = (String[]) parameters.get(1);
			minLength = Integer.parseInt((String) parameters.get(2));
			maxLength = Integer.parseInt((String) parameters.get(3));
		}
		catch (Exception e) {
			throw new InvalidParameterException();
		}
		
		IStochasticProcess process = null; 
		List<List<? extends Event<?>>> sequences = null;
		Object dataObjectProcess = GlobalDataContainer.getInstance().getData(modelname);
		if( dataObjectProcess==null ) {
			Console.println("Model " + modelname + " not found in storage.");
		}
		else if( !(dataObjectProcess instanceof IStochasticProcess) ) {
			Console.println("Object " + modelname + " not of type MarkovModel!");
		} else {
			Console.print("seqName");
			for( int length=minLength ; length<=maxLength ; length++) {
				Console.print(";all_" + length);
				Console.print(";pos_" + length);
				Console.print(";wei_" + length);
			}
			Console.println("");
			for( String sequenceName : sequenceNames ) {
				Object dataObjectSequences = GlobalDataContainer.getInstance().getData(sequenceName);
				if( dataObjectSequences==null ) {
					Console.println("Sequences " + sequenceName + " not found in storage.");
				}
				else if( !(dataObjectSequences instanceof Collection<?>) ) {
					// cannot really perform type check at runtime! this is an approximative substitute
					Console.println("Object " + sequenceName + "not of type Collection<?>!");				
				}
				
				process = (IStochasticProcess) dataObjectProcess;
				sequences = (List<List<? extends Event<?>>>) dataObjectSequences;
				Console.print(sequenceName);
				for( int length=minLength ; length<=maxLength ; length++) {
					CoverageCalculator covCalc = new CoverageCalculator(process, sequences, length);
					Console.print(";" + covCalc.getCoverageAllNoWeight());
					Console.print(";" + covCalc.getCoveragePossibleNoWeight());
					Console.print(";" + covCalc.getCoveragePossibleWeight());
				}
				Console.println("");
			}
		}
	}

	@Override
	public void help() {
		Console.println("Usage: calcCoverage <modelname> [sequenceNames] <minCovLength> <maxCovLength>");
	}

}
