//   Copyright 2012 Georg-August-Universität Göttingen, Germany
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package de.ugoe.cs.autoquest.tasktrees.nodeequality;

import de.ugoe.cs.autoquest.eventcore.IEventTarget;
import de.ugoe.cs.autoquest.eventcore.gui.IInteraction;
import de.ugoe.cs.autoquest.eventcore.gui.KeyInteraction;
import de.ugoe.cs.autoquest.eventcore.gui.KeyPressed;
import de.ugoe.cs.autoquest.eventcore.gui.KeyReleased;
import de.ugoe.cs.autoquest.eventcore.gui.KeyTyped;
import de.ugoe.cs.autoquest.eventcore.gui.MouseButtonDown;
import de.ugoe.cs.autoquest.eventcore.gui.MouseButtonInteraction;
import de.ugoe.cs.autoquest.eventcore.gui.MouseButtonUp;
import de.ugoe.cs.autoquest.eventcore.gui.MouseClick;
import de.ugoe.cs.autoquest.eventcore.gui.MouseDoubleClick;
import de.ugoe.cs.autoquest.eventcore.gui.MouseDragAndDrop;
import de.ugoe.cs.autoquest.eventcore.gui.Scroll;
import de.ugoe.cs.autoquest.eventcore.gui.TextInput;
import de.ugoe.cs.autoquest.eventcore.gui.ValueSelection;
import de.ugoe.cs.autoquest.eventcore.guimodel.IButton;
import de.ugoe.cs.autoquest.eventcore.guimodel.ICheckBox;
import de.ugoe.cs.autoquest.eventcore.guimodel.IComboBox;
import de.ugoe.cs.autoquest.eventcore.guimodel.IImage;
import de.ugoe.cs.autoquest.eventcore.guimodel.IListBox;
import de.ugoe.cs.autoquest.eventcore.guimodel.IMenu;
import de.ugoe.cs.autoquest.eventcore.guimodel.IMenuButton;
import de.ugoe.cs.autoquest.eventcore.guimodel.IRadioButton;
import de.ugoe.cs.autoquest.eventcore.guimodel.IShape;
import de.ugoe.cs.autoquest.eventcore.guimodel.IText;
import de.ugoe.cs.autoquest.eventcore.guimodel.IToolTip;
import de.ugoe.cs.autoquest.tasktrees.treeifc.IEventTask;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITaskTreeNode;

/**
 * <p>
 * This rule compares GUI event tasks (i.e. it is more concrete, than the
 * {@link EventTaskComparisonRule}). Two GUI event tasks are only equal if their event type and
 * target are equal. The returned equality is even more fine-grained for events whose type is
 * {@link TextInput} and {@link ValueSelection}. For text inputs, lexical equality is returned if
 * the same text is entered using the same key interactions. Syntactical equality is returned if
 * the same text is entered using different key interactions. Semantical equality is returned if
 * different text is entered, but into the same event target. Value selections are syntactically
 * equal, if the same value is selected. Otherwise they are semantically equal.
 * </p>
 * 
 * @author Patrick Harms
 */
public class GUIEventTaskComparisonRule implements NodeComparisonRule {
    
    /* (non-Javadoc)
     * @see NodeComparisonRule#isApplicable(ITaskTreeNode, ITaskTreeNode)
     */
    @Override
    public boolean isApplicable(ITaskTreeNode node1, ITaskTreeNode node2) {
        return
            ((node1 instanceof IEventTask) && (node2 instanceof IEventTask) &&
            (((IEventTask) node1).getEventType() instanceof IInteraction) &&
            (((IEventTask) node2).getEventType() instanceof IInteraction));
    }

    /* (non-Javadoc)
     * @see NodeComparisonRule#areLexicallyEqual(ITaskTreeNode, ITaskTreeNode)
     */
    @Override
    public boolean areLexicallyEqual(ITaskTreeNode node1, ITaskTreeNode node2) {
        NodeEquality equality = getEquality(node1, node2, NodeEquality.LEXICALLY_EQUAL);
        return (equality != null) && (equality.isAtLeast(NodeEquality.LEXICALLY_EQUAL));
    }

    /* (non-Javadoc)
     * @see NodeComparisonRule#areSyntacticallyEqual(ITaskTreeNode, ITaskTreeNode)
     */
    @Override
    public boolean areSyntacticallyEqual(ITaskTreeNode node1, ITaskTreeNode node2) {
        NodeEquality equality = getEquality(node1, node2, NodeEquality.SYNTACTICALLY_EQUAL);
        return (equality != null) && (equality.isAtLeast(NodeEquality.SYNTACTICALLY_EQUAL));
    }

    /* (non-Javadoc)
     * @see NodeComparisonRule#areSemanticallyEqual(ITaskTreeNode, ITaskTreeNode)
     */
    @Override
    public boolean areSemanticallyEqual(ITaskTreeNode node1, ITaskTreeNode node2) {
        NodeEquality equality = getEquality(node1, node2, NodeEquality.SEMANTICALLY_EQUAL);
        return (equality != null) && (equality.isAtLeast(NodeEquality.SEMANTICALLY_EQUAL));
    }

    /* (non-Javadoc)
     * @see NodeComparisonRule#compare(ITaskTreeNode, ITaskTreeNode)
     */
    @Override
    public NodeEquality compare(ITaskTreeNode node1, ITaskTreeNode node2) {
        return getEquality(node1, node2, null);
    }

    /**
     * 
     */
    private NodeEquality getEquality(ITaskTreeNode node1,
                                     ITaskTreeNode node2,
                                     NodeEquality  requiredEqualityLevel)
    {
        IEventTask task1 = (IEventTask) node1;
        IEventTask task2 = (IEventTask) node2;
        
        if (!task1.getEventTarget().equals(task2.getEventTarget())) {
            return NodeEquality.UNEQUAL;
        }
        
        IInteraction interaction1 = (IInteraction) task1.getEventType();
        IInteraction interaction2 = (IInteraction) task2.getEventType();
        
        return compareInteractions
            (interaction1, interaction2, task1.getEventTarget(), requiredEqualityLevel);
    }

    /**
     * <p>
     * compares two interactions. The method delegates to other, more specific compare method, e.g.,
     * {@link #compareTextInputs(TextInput, TextInput)} and
     * {@link #compareValueSelections(ValueSelection, ValueSelection)}, if any exist for the
     * concrete interaction types. Otherwise it uses the equals method of the interactions for
     * comparison. In this case, if the interactions equals method returns true, this method
     * returns lexical equality.
     * </p>
     *
     * @param interaction1 the first interaction to compare
     * @param interaction2 the second interaction to compare
     * @param eventTarget  the event target on which the interactions happened (used within
     *                     special comparisons like mouse clicks on buttons, where the coordinates
     *                     can be ignored)
     * 
     * @return as described
     */
    private NodeEquality compareInteractions(IInteraction interaction1,
                                             IInteraction interaction2,
                                             IEventTarget eventTarget,
                                             NodeEquality equalityLevel)
    {
        NodeEquality level = equalityLevel;
        
        if (level == null) {
            level = NodeEquality.LEXICALLY_EQUAL;
        }
        
        if (interaction1 == interaction2) {
            return NodeEquality.LEXICALLY_EQUAL;
        }
        else if ((interaction1 instanceof KeyInteraction) &&
                 (interaction2 instanceof KeyInteraction))
        {
            return compareKeyInteractions
                ((KeyInteraction) interaction1, (KeyInteraction) interaction2, level);
        }
        else if ((interaction1 instanceof MouseButtonInteraction) &&
                 (interaction2 instanceof MouseButtonInteraction))
        {
            return compareMouseButtonInteractions
                ((MouseButtonInteraction) interaction1, (MouseButtonInteraction) interaction2,
                 eventTarget, level);
        }
        else if ((interaction1 instanceof Scroll) && (interaction2 instanceof Scroll)) {
            return compareScrolls((Scroll) interaction1, (Scroll) interaction2, level);
        }
        else if ((interaction1 instanceof TextInput) && (interaction2 instanceof TextInput)) {
            return compareTextInputs
                ((TextInput) interaction1, (TextInput) interaction2, level);
        }
        else if ((interaction1 instanceof ValueSelection) &&
                 (interaction2 instanceof ValueSelection))
        {
            return compareValueSelections
                ((ValueSelection<?>) interaction1, (ValueSelection<?>) interaction2, level);
        }
        else if (interaction1.equals(interaction2)) {
            return NodeEquality.LEXICALLY_EQUAL;
        }
        else {
            return NodeEquality.UNEQUAL;
        }
    }

    /**
     * <p>
     * TODO: comment
     * </p>
     *
     * @param interaction1
     * @param interaction2
     * @param eventTarget
     * @param level
     * @return
     */
    private NodeEquality compareKeyInteractions(KeyInteraction interaction1,
                                                KeyInteraction interaction2,
                                                NodeEquality   equalityLevel)
    {
        if (((interaction1 instanceof KeyPressed) && (interaction2 instanceof KeyPressed)) ||
            ((interaction1 instanceof KeyReleased) && (interaction2 instanceof KeyReleased)) ||
            ((interaction1 instanceof KeyTyped) && (interaction2 instanceof KeyTyped)))
        {
            if ((equalityLevel.isAtLeast(NodeEquality.SYNTACTICALLY_EQUAL)) &&
                (interaction1.getKey() == interaction2.getKey()))
            {
                return NodeEquality.LEXICALLY_EQUAL;
            }
            else {
                return NodeEquality.SEMANTICALLY_EQUAL;
            }
        }
        
        return NodeEquality.UNEQUAL;
    }
    
    /**
     * <p>
     * compares two mouse drag and drops. If both drag and drops have the same start and end
     * coordinates, they are lexically equal. Otherwise, they are semantically equal.
     * </p>
     *
     * @param interaction1 the first mouse drag and drop to compare
     * @param interaction2 the second mouse drag and drop to compare
     * 
     * @return as described
     */
    private NodeEquality compareMouseDragAndDrops(MouseDragAndDrop interaction1,
                                                  MouseDragAndDrop interaction2,
                                                  NodeEquality     equalityLevel)
    {
        if (interaction1.getButton() != interaction2.getButton()) {
            return NodeEquality.UNEQUAL;
        }
        
        if (equalityLevel.isAtLeast(NodeEquality.SYNTACTICALLY_EQUAL)) {
            int x1 = interaction1.getX();
            int x1Start = interaction1.getXStart();
            int x2 = interaction2.getX();
            int x2Start = interaction2.getXStart();
            int y1 = interaction1.getY();
            int y1Start = interaction1.getYStart();
            int y2 = interaction2.getY();
            int y2Start = interaction2.getYStart();
        
            if ((x1Start == x2Start) && (x1 == x2) && (y1Start == y2Start) && (y1 == y2)) {
                return NodeEquality.LEXICALLY_EQUAL;
            }
        }
        
        return NodeEquality.SEMANTICALLY_EQUAL;
    }

    /**
     * <p>
     * compares two mouse button interactions such as clicks, mouse button down, or double clicks.
     * If both interactions have the same coordinates, they are lexically equal. Otherwise, they
     * are semantically equal. Mouse clicks for which the coordinates make no lexical difference
     * (see {@link #clickCoordinatesMakeLexicalDifference(IEventTarget)}) are treated as
     * lexically equal.
     * </p>
     *
     * @param interaction1 the first mouse button interaction to compare
     * @param interaction2 the second mouse button interaction to compare
     * @param eventTarget  the event target on which the interactions happened (used within
     *                     special comparisons like mouse clicks on buttons, where the coordinates
     *                     can be ignored)
     * 
     * @return as described
     */
    private NodeEquality compareMouseButtonInteractions(MouseButtonInteraction interaction1,
                                                        MouseButtonInteraction interaction2,
                                                        IEventTarget           eventTarget,
                                                        NodeEquality           equalityLevel)
    {
        boolean coordinatesMatch = true;
        
        if ((interaction1 instanceof MouseDragAndDrop) &&
            (interaction2 instanceof MouseDragAndDrop))
        {
            return compareMouseDragAndDrops
                ((MouseDragAndDrop) interaction1, (MouseDragAndDrop) interaction2, equalityLevel);
        }
        else if (interaction1.getButton() != interaction2.getButton()) {
            return NodeEquality.UNEQUAL;
        }
        else if (equalityLevel.isAtLeast(NodeEquality.SYNTACTICALLY_EQUAL) &&
                 clickCoordinatesMakeLexicalDifference(eventTarget))
        {
            int x1 = interaction1.getX();
            int x2 = interaction2.getX();
            int y1 = interaction1.getY();
            int y2 = interaction2.getY();

            if ((x1 != x2) || (y1 != y2)) {
                coordinatesMatch = false;
            }
        }
        
        // up to now, they can be equal. Now check the types. Do it as last action as these
        // checks take the most time and should, therefore, only be done latest
        if (((interaction1 instanceof MouseClick) && (interaction2 instanceof MouseClick)) ||
            ((interaction1 instanceof MouseDoubleClick) &&
             (interaction2 instanceof MouseDoubleClick)) ||
            ((interaction1 instanceof MouseButtonDown) &&
             (interaction2 instanceof MouseButtonDown)) ||
            ((interaction1 instanceof MouseButtonUp) &&
             (interaction2 instanceof MouseButtonUp)))
        {
            if (coordinatesMatch) {
                return NodeEquality.LEXICALLY_EQUAL;
            }
            else {
                return NodeEquality.SEMANTICALLY_EQUAL;
            }
        }
        
        return NodeEquality.UNEQUAL;
    }

    /**
     * <p>
     * compares two mouse button interactions such as clicks, mouse button down, or double clicks.
     * If both interactions have the same coordinates, they are lexically equal. Otherwise, they
     * are semantically equal. Mouse clicks for which the coordinates make no lexical difference
     * (see {@link #clickCoordinatesMakeLexicalDifference(IEventTarget)}) are treated as
     * lexically equal.
     * </p>
     *
     * @param interaction1 the first mouse button interaction to compare
     * @param interaction2 the second mouse button interaction to compare
     * @param eventTarget  the event target on which the interactions happened (used within
     *                     special comparisons like mouse clicks on buttons, where the coordinates
     *                     can be ignored)
     * 
     * @return as described
     */
    private NodeEquality compareScrolls(Scroll       interaction1,
                                        Scroll       interaction2,
                                        NodeEquality equalityLevel)
    {
        if (equalityLevel.isAtLeast(NodeEquality.SYNTACTICALLY_EQUAL)) {
            int x1 = interaction1.getXPosition();
            int x2 = interaction2.getXPosition();
            int y1 = interaction1.getYPosition();
            int y2 = interaction2.getYPosition();
        
            if ((x1 == x2) && (y1 == y2)) {
                return NodeEquality.LEXICALLY_EQUAL;
            }
        }
        
        return NodeEquality.SEMANTICALLY_EQUAL;
    }

    /**
     * <p>
     * compares two text inputs. If both text inputs have the same entered text and text input
     * events, they are lexically equal. If they only have the same entered text, they are
     * syntactically equal. If they are only both text inputs, they are semantically equal.
     * (the equality of the event targets is checked beforehand).
     * </p>
     *
     * @param interaction1 the first text input to compare
     * @param interaction2 the second text input to compare
     * 
     * @return as described
     */
    private NodeEquality compareTextInputs(TextInput    interaction1,
                                           TextInput    interaction2,
                                           NodeEquality equalityLevel)
    {
        switch (equalityLevel) {
            case LEXICALLY_EQUAL:
                if (interaction1.getTextInputEvents().equals(interaction2.getTextInputEvents())) {
                    return NodeEquality.LEXICALLY_EQUAL;
                }
                // fall through
            case SYNTACTICALLY_EQUAL:
                if (interaction1.getEnteredText().equals(interaction2.getEnteredText())) {
                    return NodeEquality.SYNTACTICALLY_EQUAL;
                }
                // fall through
            case SEMANTICALLY_EQUAL:
                return NodeEquality.SEMANTICALLY_EQUAL;
            default:
                return NodeEquality.UNEQUAL;
        }
    }

    /**
     * <p>
     * compares two value selections. If both value selections have the same selected value, they
     * are syntactically equal, otherwise they are semantically equal.
     * (the equality of the event targets is checked beforehand).
     * </p>
     *
     * @param interaction1 the first value selection to compare
     * @param interaction2 the second value selection to compare
     * 
     * @return as described
     */
    private NodeEquality compareValueSelections(ValueSelection<?> interaction1,
                                                ValueSelection<?> interaction2,
                                                NodeEquality      equalityLevel)
    {
        if (equalityLevel.isAtLeast(NodeEquality.SYNTACTICALLY_EQUAL)) {
            Object value1 = interaction1.getSelectedValue();
            Object value2 = interaction2.getSelectedValue();
        
            if ((value1 == value2) || ((value1 != null) && (value1.equals(value2)))) {
                return NodeEquality.LEXICALLY_EQUAL;
            }
        }
        
        return NodeEquality.SEMANTICALLY_EQUAL;
    }

    /**
     * <p>
     * Checks, if the coordinates of a click or double click on the provided event target makes
     * a lexical difference. Mouse clicks and double clicks on buttons, check boxes,
     * combo boxes, images, list boxes, menu buttons, radio buttons, shapes, uneditable text,
     * and tool tips have no lexical difference as long as they happen on the same event target.
     * The concrete coordinates are not relevant.
     * </p>
     *
     * @param eventTarget the event target on which the interaction occurred
     * 
     * @return if the coordinates are important to be considered for clicks and double clicks,
     *         false else
     */
    private boolean clickCoordinatesMakeLexicalDifference(IEventTarget eventTarget) {
        if ((eventTarget instanceof IButton) ||
            (eventTarget instanceof ICheckBox) ||
            (eventTarget instanceof IComboBox) ||
            (eventTarget instanceof IImage) ||
            (eventTarget instanceof IListBox) ||
            (eventTarget instanceof IMenu) ||
            (eventTarget instanceof IMenuButton) ||
            (eventTarget instanceof IRadioButton) ||
            (eventTarget instanceof IShape) ||
            (eventTarget instanceof IText) ||
            (eventTarget instanceof IToolTip))
        {
            return false;
        }
        else {
            return true;
        }
    }

}
