// Module    : $RCSfile: KeyInteractionTargetCorrector.java,v $
// Version   : $Revision: 0.0 $  $Author: pharms $  $Date: 29.08.2012 $
// Project   : quest-core-events
// Creation  : 2012 by pharms
// Copyright : Patrick Harms, 2012
package de.ugoe.cs.quest.eventcore.gui;

import java.util.LinkedList;
import java.util.List;

import de.ugoe.cs.quest.eventcore.Event;
import de.ugoe.cs.quest.eventcore.guimodel.IGUIElement;

/**
 * <p>
 * This class iterates the provided sequence 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 the
 * provided sequence. Events changing the keyboard focus are discarded herewith.
 * </p>
 * 
 * @version $Revision: $ $Date: 29.08.2012$
 * @author 2012, last modified by $Author: pharms$
 */
public class KeyInteractionTargetCorrector {
    
    /**
     * <p>
     * This method performs the work described in the description of the class. A new list is
     * instantiated and returned. This list is filled with the events provided by the sequence
     * being the parameter of the method except for key interaction events. Those are replaced
     * by a new event with the identical event type but the corrected event target.
     * </p>
     * 
     * @param sequence the event sequence to correct the key interactions targets in
     * 
     * @return the resulting sequence, in which key interactions have the correct target, i.e.
     *         the GUI element having the keyboard focus
     */
    public List<Event> correctKeyInteractionTargets(List<Event> sequence) {
        List<Event> resultingSequence = new LinkedList<Event>();
        IGUIElement currentKeyboardFocusGUIElement = null;
        
        for (Event event : sequence) {
            if (event.getTarget() instanceof IGUIElement) {
                if (event.getType() instanceof KeyboardFocusChange) {
                    currentKeyboardFocusGUIElement = (IGUIElement) event.getTarget();
                    event = null;
                }
                else if (event.getType() instanceof KeyInteraction) {
                    if (currentKeyboardFocusGUIElement == null) {
                        currentKeyboardFocusGUIElement = (IGUIElement) event.getTarget();
                    }
                    
                    if (!currentKeyboardFocusGUIElement.equals(event.getTarget())) {
                        event = new Event(event.getType(), currentKeyboardFocusGUIElement);
                    }
                }
            }
            
            if (event != null) {
                resultingSequence.add(event);
            }
        }
        
        return resultingSequence;
    }
}
