//   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.usability2.rules.metrics;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;

import com.google.common.base.Optional;

import de.ugoe.cs.autoquest.eventcore.Event;
import de.ugoe.cs.autoquest.eventcore.IEventTarget;
import de.ugoe.cs.autoquest.eventcore.IEventType;
import de.ugoe.cs.autoquest.eventcore.gui.Scroll;
import de.ugoe.cs.autoquest.usability.EvaluationMethodCaller;
import de.ugoe.cs.autoquest.usability.result.UsabilityProblemDescription;
import de.ugoe.cs.autoquest.usability.result.UsabilityProblemDescriptionResolver;
import de.ugoe.cs.autoquest.usability.rules.UsabilityMetric;
import de.ugoe.cs.autoquest.usability.rules.UsabilityRule;
import de.ugoe.cs.autoquest.plugin.usability2.rules.metrics.visitor.AbstractMetricVisitor;
import de.ugoe.cs.autoquest.tasktrees.treeifc.IEventTaskInstance;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITaskInstance;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITaskModel;
import de.ugoe.cs.autoquest.tasktrees.treeifc.IUserSession;

/**
 * <p>
 * Metric, which measures directed scrolling compared to back-and-forth type of scrolling. This is
 * done by calculating the absolute distance scrolled compared to the relative >>>
 * </p>
 * 
 * @author Konni Hartmann
 */
public class RedundantScrollingMetric extends UsabilityRule implements UsabilityMetric {

    /**
     * <p>
     * Constructor. Creates a new {@code TextInputRatioMetric} for a given task model.
     * </p>
     * 
     * @param taskTree
     */
    public RedundantScrollingMetric(ITaskModel taskModel) {
        super(taskModel);
        this.name = "RedundantScrollingMetric";
        this.defect =
            new UsabilityProblemDescriptionResolver().descriptionFor(this.getClass()
                .getSimpleName());
    }

    /*
     * (non-Javadoc)
     * 
     * @see de.ugoe.cs.autoquest.usability.rules.UsabilityRule#check()
     */
    @Override
    public Optional<UsabilityProblemDescription> calculate() {
        Collection<IUserSession> ses = taskModel.getUserSessions();
        float evaluationMetric = calculateEvaluationMetric(ses);
        return this.defect.isPresent(evaluationMetric);
    }

    class PerTargetData extends HashMap<IEventTarget, List<Double>> {

        /**  */
        private static final long serialVersionUID = 4961605116656275571L;

        void push(Data data) {
            for (java.util.Map.Entry<IEventTarget, DataEntry> entry : data.map.entrySet()) {
                double absDistance = entry.getValue().distance;
                if (absDistance > 0) {
                    List<Double> list = this.get(entry.getKey());
                    if (list == null) {
                        list = new ArrayList<Double>();
                        this.put(entry.getKey(), list);
                    }

                    double relDistance = entry.getValue().getRelativeDistance();
                    double maxDistance = entry.getValue().getMaxDistance();
                    double value = (absDistance - relDistance) / maxDistance;
                    list.add(value);
                }
            }
        }

        public float calculateMetric() {
            double result = 0;

            IEventTarget maxTarget = null;
            DescriptiveStatistics maxStats = null;

            int N = 3;
            IEventTarget maxNTarget = null;
            DescriptiveStatistics maxNStats = null;

            for (java.util.Map.Entry<IEventTarget, List<Double>> entry : this.entrySet()) {
                List<Double> values = entry.getValue();

                if (values.size() == 0)
                    continue;

                DescriptiveStatistics currentStats = new DescriptiveStatistics();

                for (Double v : values) {
                    currentStats.addValue(v);
                }

                if (maxStats == null || (currentStats.getMean() > maxStats.getMean())) {
                    maxTarget = entry.getKey();
                    maxStats = currentStats;
                }

                if (maxNStats == null ||
                    ((currentStats.getN() >= N) && (currentStats.getMean() > maxNStats.getMean())))
                {
                    maxNTarget = entry.getKey();
                    maxNStats = currentStats;
                }

            }

            if (maxTarget != null) {
                System.out.printf("(RSM) Highest ranking target: %s\n%s\n",
                                  maxTarget.getStringIdentifier(), maxStats);
                result = maxStats.getMean();
            }
            else
                System.out.println("(RSM) No target found");

            if (maxNTarget != null)
                System.out.printf("(RSM) Highest ranking target (>=%d): %s\n%s\n", N,
                                  maxNTarget.getStringIdentifier(), maxNStats);

            return (float) (result);
        }

    }

    class DataEntry {
        int posX = 0, posY = 0;
        int maxPosX = 0, maxPosY = 0;
        double distance = 0;

        double getRelativeDistance() {
            return Math.sqrt(posX * posX + posY * posY);
        }

        double getMaxDistance() {
            return Math.sqrt(maxPosX * maxPosX + maxPosY * maxPosY);
        }

        public void addScrollPoint(int scrollX, int scrollY) {
            if (scrollX == -1)
                scrollX = 0;
            if (scrollY == -1)
                scrollY = 0;

            int xDiff = scrollX - this.posX;
            int yDiff = scrollY - this.posY;

            this.posX = scrollX;
            this.posY = scrollY;

            if (this.maxPosX < scrollX)
                this.maxPosX = scrollX;

            if (this.maxPosY < scrollY)
                this.maxPosY = scrollY;

            double dist = Math.sqrt(xDiff * xDiff + yDiff * yDiff);
            this.distance += dist;
        }
    }

    class Data {
        Map<IEventTarget, DataEntry> map = new HashMap<IEventTarget, DataEntry>();

        void updateTarget(IEventTarget target, Scroll scroll) {
            DataEntry data = map.get(target);
            if (data == null) {
                data = new DataEntry();
                map.put(target, data);
            }

            int scrollX = scroll.getXPosition();
            int scrollY = scroll.getYPosition();

            data.addScrollPoint(scrollX, scrollY);
        }
    }

    private float calculateEvaluationMetric(Collection<IUserSession> tasks) {
        PerTargetData allData = new PerTargetData();

        for (IUserSession s : tasks) {
            Collection<ITaskInstance> instances = s.getExecutedTasks();

            final Data data = new Data();

            for (ITaskInstance iTaskInstance : instances) {

                AbstractMetricVisitor visitor = new AbstractMetricVisitor() {
                    @Override
                    public void visit(IEventTaskInstance instance) {
                        Event event = instance.getEvent();
                        IEventType type = event.getType();
                        if (type instanceof Scroll) {
                            Scroll scroll = (Scroll) type;
                            data.updateTarget(event.getTarget(), scroll);
                        }
                    }
                };

                visitor.visit(iTaskInstance);
            }
            allData.push(data);
        }

        return allData.calculateMetric();
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * de.ugoe.cs.autoquest.usability.rules.UsabilityRule#callEvaluationMetho(de.ugoe.cs.autoquest
     * .usability.EvaluationMethodCaller)
     */
    @Override
    public Optional<UsabilityProblemDescription> callEvaluationMethod(EvaluationMethodCaller evaluationMethodCaller)
    {
        return evaluationMethodCaller.check(this);
    }
}
