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

import static de.ugoe.cs.autoquest.usability.taskmodel.filter.types.EventTypeFilter.TEXT_INPUT;
import static de.ugoe.cs.autoquest.usability.util.TextInputUtil.aggregateEnteredTextFromTextInputs;

import java.util.List;

import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multisets;

import de.ugoe.cs.autoquest.tasktrees.treeifc.ITask;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITaskModel;
import de.ugoe.cs.autoquest.usability.EvaluationMethodCaller;
import de.ugoe.cs.autoquest.usability.result.UsabilityProblemDescriptionResolver;
import de.ugoe.cs.autoquest.usability.result.UsabilityProblemDescription;
import de.ugoe.cs.autoquest.usability.rules.UsabilityMetric;
import de.ugoe.cs.autoquest.usability.rules.UsabilityRule;
import de.ugoe.cs.autoquest.usability.taskmodel.filter.FilterResult;
import de.ugoe.cs.autoquest.usability.taskmodel.filter.IterativeDFSFilterStrategy;
import de.ugoe.cs.autoquest.usability.taskmodel.filter.types.TaskModelFilter;

/**
 * <p>
 * Metric, which measures either the repetition of entered words or the maximum repetition of a
 * single word.
 * </p>
 * 
 * @author Alexander Deicke
 */
public class TextInputEntryRepetitionsMetric extends UsabilityRule implements UsabilityMetric {

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

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

    /**
     * 
     * <p>
     * Filters all text input events from task model.
     * </p>
     * 
     * @return {@code FilterResult}
     */
    private FilterResult extractNodesFromTaskTree() {
        return new TaskModelFilter(new IterativeDFSFilterStrategy()).filterByEventType(TEXT_INPUT)
            .from(this.taskModel);
    }

    /**
     * 
     * <p>
     * Calculates the metric.
     * </p>
     * 
     * @param textInputEvents
     *            all text input events
     * @return either number of repeated words or the number of repetitions of the most entered word
     */
    private float calculateEvaluationMetric(List<ITask> textInputEvents) {
        Multiset<String> enteredTextFragments = aggregateEnteredTextFromTextInputs(textInputEvents);
        Multiset<String> orderedTextFragmentsWithMultipleOccurences =
            onlyTextFragmentsWithMultipleOccurences(enteredTextFragments);
        if (orderedTextFragmentsWithMultipleOccurences.isEmpty())
            return 0;
        String wordWithHighestRepetitionInTextFragments =
            orderedTextFragmentsWithMultipleOccurences.iterator().next();
        int numberOfRepeatedWords = orderedTextFragmentsWithMultipleOccurences.entrySet().size();
        int maxRepetitions =
            orderedTextFragmentsWithMultipleOccurences
                .count(wordWithHighestRepetitionInTextFragments);
        return Math.max(numberOfRepeatedWords, maxRepetitions - 1);
    }

    /**
     * 
     * <p>
     * Return only words, which at least entered twice.
     * </p>
     * 
     * @param allTextInputs
     *            all text input events
     * @return all word, which used min. twice
     */
    private Multiset<String> onlyTextFragmentsWithMultipleOccurences(final Multiset<String> allTextInputs)
    {
        return Multisets.copyHighestCountFirst(Multisets.filter(allTextInputs,
                                                                new Predicate<String>() {

                                                                    @Override
                                                                    public boolean apply(String word)
                                                                    {
                                                                        return allTextInputs
                                                                            .count(word) > 1;
                                                                    }

                                                                }));
    }

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

}
