//   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.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

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.TextInput;
import de.ugoe.cs.autoquest.eventcore.gui.ValueSelection;
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 SameTargetEditingMetric extends UsabilityRule implements UsabilityMetric {

    /**
     * <p>
     * Constructor. Creates a new {@code TextInputRatioMetric} for a given task model.
     * </p>
     * 
     * @param taskTree
     */
    public SameTargetEditingMetric(ITaskModel taskModel) {
        super(taskModel);
        this.name = "SameTargetEditingMetric";
        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 Data {
        Map<IEventTarget, Integer> map = new HashMap<IEventTarget, Integer>();
        
        void updateTarget(IEventTarget target, IEventType type) {
            Integer data = map.get(target);
            if(data == null) {
                data = 0;
            }
            data++;
            map.put(target, data);
        }
    }
  
    private float calculateEvaluationMetric(Collection<IUserSession> tasks) {
        int maxEditsPerTarget = 0;
        IEventTarget maxTarget = null;
        
        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 TextInput ||
                            type instanceof ValueSelection) {
                            data.updateTarget(event.getTarget(), type);
                        }
                    }
                };
                
                visitor.visit(iTaskInstance);
            }

            for (Entry<IEventTarget, Integer> entry : data.map.entrySet()) {
                if (entry.getValue() > maxEditsPerTarget) {
                    maxTarget = entry.getKey();
                    maxEditsPerTarget = entry.getValue();
                }
            }
        }

        if (maxTarget != null)
            System.out.printf("(STE) Highest ranking target: %s (%d) \n", maxTarget.getStringIdentifier(), maxEditsPerTarget);
        else
            System.out.println("(STE) No target found");
        
        return maxEditsPerTarget;
    }

    /*
     * (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);
    }
}
