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

import java.security.InvalidParameterException;
import java.util.Collection;
import java.util.LinkedList;
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.eventcore.gui.KeyInteractionTargetCorrector;
import de.ugoe.cs.util.console.Command;
import de.ugoe.cs.util.console.GlobalDataContainer;

/**
 * <p>
 * This command iterates the provided sequences and sets the target of all key interaction events
 * to the GUI element having the current keyboard focus. The current keyboard focus is determined
 * either by keyboard focus events or by using the target of the first key interaction in a
 * sequence.
 * </p>
 * 
 * @author Patrick Harms
 * @version 1.0
 */
public class CMDcorrectKeyInteractionTargets implements Command {

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

    /*
     * (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 newSequencesName;
        try {
            sequencesName = (String) parameters.get(0);
            if (parameters.size() > 1) {
                newSequencesName = (String) parameters.get(1);
            }
            else {
                newSequencesName = sequencesName;
            }
        }
        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;

        Collection<List<Event>> newSequences = new LinkedList<List<Event>>();
        
        for (List<Event> sequence : sequences) {
            newSequences.add
                (new KeyInteractionTargetCorrector().correctKeyInteractionTargets(sequence));
        }

        if (GlobalDataContainer.getInstance().addData(newSequencesName, newSequences)) {
            CommandHelpers.dataOverwritten(sequencesName);
        }
        
    }

}
