package de.ugoe.cs.autoquest.usability.tasktree.filter;

import java.util.Stack;

import com.google.common.base.Predicate;

import de.ugoe.cs.autoquest.eventcore.IEventTarget;
import de.ugoe.cs.autoquest.eventcore.IEventType;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITaskTree;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITaskTreeNode;

public class IterativeDFSFilterStrategy implements TaskTreeFilterStrategy {
    
    private FilterStatistic filterStatistic;
    
    @SuppressWarnings("unchecked")
    @Override
    public FilterStatistic filter(ITaskTree taskTree, EventTargetFilter eventTarget) {
        Predicate<IEventTarget> filterPredicate = eventTarget.filterPredicate();
        this.filterStatistic = new FilterStatistic(filterPredicate);
        traverse(taskTree);
        return this.filterStatistic;
    }

    @SuppressWarnings("unchecked")
    @Override
    public FilterStatistic filter(ITaskTree taskTree, EventTypeFilter eventType) {
        Predicate<IEventType> filterPredicate = eventType.filterPredicate();
        this.filterStatistic = new FilterStatistic(filterPredicate);
        traverse(taskTree);
        return this.filterStatistic;
    }
    
    private void traverse(ITaskTree taskTree) {
        Stack<ITaskTreeNode> unvisitedNodes = new Stack<ITaskTreeNode>();
        unvisitedNodes.push(taskTree.getRoot());
        while(stillUnvisitedNodes(unvisitedNodes)) {
            ITaskTreeNode node = unvisitedNodes.pop();
            processCurrentNode(node);
            processChildrenOfCurrentNode(unvisitedNodes, node);
        }
    }

    private boolean stillUnvisitedNodes(Stack<ITaskTreeNode> unvisitedNodes) {
        return !unvisitedNodes.isEmpty();
    }

    private void processCurrentNode(ITaskTreeNode node) {
        this.filterStatistic.addNode(node);
    }
    
    private void processChildrenOfCurrentNode(Stack<ITaskTreeNode> unvisitedNodes,
                                              ITaskTreeNode node) {
        for(ITaskTreeNode child : node.getChildren()) {
            unvisitedNodes.push(child);
        }
    }

}
