//   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.usability;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.ugoe.cs.autoquest.eventcore.Event;
import de.ugoe.cs.autoquest.eventcore.guimodel.IGUIElement;
import de.ugoe.cs.autoquest.tasktrees.treeifc.DefaultTaskInstanceTraversingVisitor;
import de.ugoe.cs.autoquest.tasktrees.treeifc.IEventTaskInstance;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ISequence;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITask;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITaskInstance;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITaskModel;

/**
 * TODO comment
 * 
 * @version $Revision: $ $Date: 16.07.2012$
 * @author 2012, last modified by $Author: pharms$
 */
public class TargetDistanceRule implements UsabilityEvaluationRule {
    
    /** pattern for parsing target position parameter values */
    private Pattern targetPositionPattern = Pattern.compile
            ("\\(\\s*(-?\\d*(\\.\\d*)?),\\s*(-?\\d*(\\.\\d*)?),\\s*(-?\\d*(\\.\\d*)?)\\s*\\)");

    /*
     * (non-Javadoc)
     * 
     * @see de.ugoe.cs.usability.UsabilityEvaluationRule#evaluate(TaskTree)
     */
    @Override
    public UsabilityEvaluationResult evaluate(ITaskModel taskModel) {
        UsabilityEvaluationResult results = new UsabilityEvaluationResult(taskModel);

        checkForTargetDistances(results, taskModel);

        return results;
    }

    /**
     * 
     */
    private void checkForTargetDistances(UsabilityEvaluationResult results, ITaskModel taskModel) {
        for (ITask task : taskModel.getTasks()) {
            if (task instanceof ISequence) {

                int cummulativeNoOfHops = 0;
                int cummulativeDistance = 0;

                for (ITaskInstance instance : task.getInstances()) {
                    int[] stats = getTargetDistance(instance);
                    cummulativeNoOfHops += stats[0] - 1;
                    cummulativeDistance += stats[1];
                }

                createHighTargetDisanceIfRequired
                    (cummulativeNoOfHops, cummulativeDistance, task, results, taskModel);
            }
        }
    }

    /**
     *
     */
    private int[] getTargetDistance(ITaskInstance instance) {
        List<Event> events = new LinkedList<Event>();
        getEvents(instance, events);
        int noOfEvents = events.size();
        int distance = 0;
        
        while (events.size() > 1) {
            distance += getDistance(events.get(0), events.get(1));
            events.remove(0);
        }
        
        return new int[] { noOfEvents, distance };
    }

    /**
     *
     */
    private int getDistance(Event event1, Event event2) {
        String location1 = event1.getParameter("targetPosition");
        String location2 = event2.getParameter("targetPosition");
        
        if ((location1 != null) && (location2 != null)) {
            Matcher matcher1 = targetPositionPattern.matcher(location1);
            Matcher matcher2 = targetPositionPattern.matcher(location2);
            if (matcher1.matches() && matcher2.matches()) {
                try {
                    double x =
                        Double.parseDouble(matcher2.group(1)) - Float.parseFloat(matcher1.group(1));
                    
                    double y =
                        Double.parseDouble(matcher2.group(3)) - Float.parseFloat(matcher1.group(3));
                    
                    double z =
                        Double.parseDouble(matcher2.group(5)) - Float.parseFloat(matcher1.group(5));
                    
                    return (int) (100 * Math.sqrt(x*x + y*y + z*z));
                }
                catch (NumberFormatException e) {
                    // ignore and just continue with other variants.
                }
            }
        }
        
        if ((event1.getTarget() instanceof IGUIElement) &&
            (event2.getTarget() instanceof IGUIElement))
        {
            IGUIElement target1 = (IGUIElement) event1.getTarget();
            IGUIElement target2 = (IGUIElement) event2.getTarget();
            return (int) (1000 * target1.getDistanceTo(target2));
        }
        
        if (event1.getTarget().equals(event2.getTarget())) {
            return 0;
        }
        
        return 1000;
    }

    /**
     *
     */
    private void getEvents(ITaskInstance instance, final List<Event> events) {
        instance.accept(new DefaultTaskInstanceTraversingVisitor() {
            @Override
            public void visit(IEventTaskInstance eventTaskInstance) {
                if (!(ActionClassifier.isInefficient(eventTaskInstance.getEvent()))) {
                    events.add(eventTaskInstance.getEvent());
                }
            }
        });
    }

    /**
     *
     */
    private void createHighTargetDisanceIfRequired(int                       cummulativeNoOfHops,
                                                   int                       cummulativeDistance,
                                                   ITask                     task,
                                                   UsabilityEvaluationResult results,
                                                   ITaskModel                taskModel)
    {
        if ((cummulativeDistance > 0) && (cummulativeNoOfHops > 0)) {
            int ratio = cummulativeDistance / cummulativeNoOfHops;

            // for HTML: 800 means not even on the same server
            // for HTML: 600 means not on the same page
            // for HTML: 501 means in average not on the same page
            UsabilitySmellIntensity severity =
                UsabilitySmellIntensity.getIntensity(ratio, task, taskModel);

            if (severity != null) {
                double averageNoOfGUIElements =
                    ((double) cummulativeNoOfHops / task.getInstances().size()) + 1;
                
                Map<String, Object> parameters = new HashMap<String, Object>();
                parameters.put("task", task);
                parameters.put("noOfGUIElements", averageNoOfGUIElements);
                parameters.put("distance", ((double) ratio / 1000));

                results.addSmell
                    (task, severity, UsabilitySmellDescription.HIGH_TARGET_DISTANCE, parameters);
            }
        }
    }

}
