//   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.plugin.html.eventcore;

import java.util.Map;
import java.util.logging.Level;

import de.ugoe.cs.autoquest.eventcore.IEventType;
import de.ugoe.cs.autoquest.eventcore.gui.IInteraction;
import de.ugoe.cs.autoquest.eventcore.gui.KeyPressed;
import de.ugoe.cs.autoquest.eventcore.gui.KeyboardFocusChange;
import de.ugoe.cs.autoquest.eventcore.gui.MouseButtonInteraction;
import de.ugoe.cs.autoquest.eventcore.gui.MouseClick;
import de.ugoe.cs.autoquest.eventcore.gui.MouseDoubleClick;
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.ICheckBox;
import de.ugoe.cs.autoquest.eventcore.guimodel.IComboBox;
import de.ugoe.cs.autoquest.eventcore.guimodel.IGUIElement;
import de.ugoe.cs.autoquest.eventcore.guimodel.IRadioButton;
import de.ugoe.cs.autoquest.eventcore.guimodel.ITextArea;
import de.ugoe.cs.autoquest.eventcore.guimodel.ITextField;
import de.ugoe.cs.autoquest.keyboardmaps.VirtualKey;
import de.ugoe.cs.util.console.Console;

/**
 * <p>
 * convenience class to instantiate the correct event type based on an event name, event parameters,
 * and the target GUI element.
 * </p>
 * 
 * @author Patrick Harms
 * @author Fabian Glaser
 */
public class HTMLEventTypeFactory {
    
    /**
     * <p>
     * single instance
     * </p>
     */
    private static HTMLEventTypeFactory instance = new HTMLEventTypeFactory();

    /**
     * <p>
     * private constructor to implement correct singleton
     * </p>
     */
    private HTMLEventTypeFactory() {}

    /**
     * <p>
     * singleton retrieval
     * </p>
     */
    public static HTMLEventTypeFactory getInstance() {
        return instance;
    }

    /**
     * <p>
     * returns the event type for the given event name, the parameters as well as the target GUI
     * element
     * </p>
     *
     * @param eventName       the name of the event, e.g., onscroll
     * @param eventParameters the parameters of the event, e.g., scroll coordinates
     * @param guiElement      the target GUI element of the event (required for some event type
     *                        differentiation
     *                        
     * @return the event type matching the proviced parameters
     * 
     * @throws IllegalArgumentException if the provided parameters in their combination do not
     *                                  correctly specify an event type 
     */
    public IEventType getEventType(String              eventName,
                                   Map<String, String> eventParameters, 
                                   IGUIElement         guiElement)
    {
        IInteraction result = null;

        if ("onscroll".equals(eventName)) {
            int[] coordinates =
                getCoordinateParameter("scrollX", "scrollY", eventName, eventParameters);
            
            result = new Scroll(coordinates[0], coordinates[1]);
        }
        else if ("onclick".equals(eventName)) {
            int[] coordinates = getCoordinateParameter("X", "Y", eventName, eventParameters);
            result =
                new MouseClick(MouseButtonInteraction.Button.LEFT, coordinates[0], coordinates[1]);
        }
        else if ("ondblclick".equals(eventName)) {
            int[] coordinates = getCoordinateParameter("X", "Y", eventName, eventParameters);
            result = new MouseDoubleClick
                (MouseButtonInteraction.Button.LEFT, coordinates[0], coordinates[1]);
        }
        else if ("onchange".equals(eventName)) {
            String value = eventParameters.get("selectedValue");
            
            if ((guiElement instanceof ITextArea) || (guiElement instanceof ITextField)) {
                result = new TextInput(value, null);
            }
            else if ((guiElement instanceof IRadioButton) || (guiElement instanceof ICheckBox) ||
                     (guiElement instanceof IComboBox))
            {
                result = new ValueSelection<String>(value);
            }
            else {
                throw new IllegalArgumentException("can not handle onchange events on GUI " +
                                                   "elements of type " + guiElement.getClass()); 
            }
        }
        else if ("onkeydown".equals(eventName)) {
            try {
                int key = Integer.parseInt(eventParameters.get("key"));
                result = new KeyPressed(VirtualKey.valueOf(key));
            }
            catch (NumberFormatException e) {
                throw new IllegalArgumentException("the key id provided by an " + eventName +
                                                   " is no correct integer");
            }
        }
        else if ("onfocus".equals(eventName)) {
            result = new KeyboardFocusChange();
        }
        else if ("onunload".equals(eventName) || "onbeforeunload".equals(eventName) ||
                 "onpagehide".equals(eventName) || "onpageshow".equals(eventName) ||
                 "onsubmit".equals(eventName) || "onselect".equals(eventName) ||
                 "onreset".equals(eventName))
        {
            Console.traceln(Level.FINE, "Ignored event name \"" + eventName + "\"");
        }
        else {
            throw new IllegalArgumentException("unknown event name: \"" + eventName + "\"");
        }
        return result;
    }

    /**
     * <p>
     * convenience method to retrieve coordinates from the event parameters.
     * </p>
     */
    private int[] getCoordinateParameter(String              xParamName,
                                         String              yParamName,
                                         String              eventName,
                                         Map<String, String> eventParameters)
    {
        String xCoord = eventParameters.get(xParamName);
        if (xCoord == null) {
            Console.printerrln("eventParameters do not contain " + xParamName + " coordinate.");
            xCoord = "0";
        }

        String yCoord = eventParameters.get(yParamName);
        if (yCoord == null) {
            Console.printerrln("eventParameters do not contain " + yParamName + " coordinate.");
            yCoord = "0";
        }

        try {
            return new int[]
                { Integer.parseInt(xCoord), Integer.parseInt(yCoord) };
        }
        catch (NumberFormatException e) {
            throw new IllegalArgumentException("the coordinates provided by an " + eventName +
                " event are no numbers");
        }
    }
    
    
    
}
