package at.oefai.aaa.agent.jam;

import java.io.Serializable;

import at.oefai.aaa.agent.jam.types.Binding;
import at.oefai.aaa.agent.jam.types.DList;
import at.oefai.aaa.agent.jam.types.Value;

/**
 * Achieve Predicate (an Achieve-goal expression evaluable to true/false).
 * @author Marc Huber
 * @author Jaeho Lee
 */
class PredicateAchieve extends Predicate implements Serializable {

    private final IntentionStructure intentionStructure;

    /** Primary constructor. */
    PredicateAchieve(final String name, final Relation relation, final IntentionStructure pIntentionStructure) {
        super(name, relation);
        this.intentionStructure = pIntentionStructure;
    }

    // Member functions

    /** Go through the goals in the Intention Structure and see if there are any that match. */
    public Value eval(final Binding binding) {
        int stackLoop;
        Goal stackGoal;
        DList<Goal> stacks = this.intentionStructure.getToplevelGoals();

        for (stackLoop = 1; stackLoop <= stacks.size(); stackLoop++) {
            stackGoal = stacks.getNth(stackLoop);

            while (stackGoal != null) {
                if (stackGoal.matchRelation(this.relation, binding)) {
                    return Value.TRUE;
                }
                stackGoal = stackGoal.getSubgoal();
            }
        }
        return Value.FALSE;
    }

}

