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

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.tasktrees.manager.TaskTreeManager;
import de.ugoe.cs.quest.tasktrees.treeifc.ITaskTree;
import de.ugoe.cs.util.console.Command;
import de.ugoe.cs.util.console.GlobalDataContainer;

/**
 * <p>
 * This command generates a task tree based on the provided sequences. It uses the
 * {@link TaskTreeManager} for this purpose. Please consult the documentation of the task tree
 * manager for more details.
 * </p>
 * 
 * @author Patrick Harms
 * @version 1.0
 */
public class CMDgenerateTaskTree implements Command {

    /*
     * (non-Javadoc)
     * 
     * @see de.ugoe.cs.util.console.Command#help()
     */
    @Override
    public String help() {
        return "generateTaskTree <sequences> {<tasktree>}";
    }

    /*
     * (non-Javadoc)
     * 
     * @see de.ugoe.cs.util.console.Command#run(java.util.List)
     */
    @SuppressWarnings("unchecked")
    @Override
    public void run(List<Object> parameters) {
        String sequencesName;
        String tasktreeName;
        try {
            sequencesName = (String) parameters.get(0);
            if (parameters.size() > 1) {
                tasktreeName = (String) parameters.get(1);
            }
            else {
                tasktreeName = "tasktree";
            }
        }
        catch (Exception e) {
            throw new InvalidParameterException("must provide a sequences name");
        }

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

        sequences = (Collection<List<Event>>) dataObject;
        
        ITaskTree taskTree = new TaskTreeManager().createTaskTree(sequences);
        
        if (GlobalDataContainer.getInstance().addData(tasktreeName, taskTree)) {
            CommandHelpers.dataOverwritten(sequencesName);
        }
        
    }

}
