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.Variable;

/**
 * A built-in JAM primitive action for binding plan variables with world model entries.
 * and providing a means for access to ALL of the matching relations rather than just one as RETRIEVE does.
 * @author Marc Huber
 */
class NextFactAction extends WorldModelAction implements Serializable {
    private final Variable variable;

    /** Constructor w/ relation to retrieve from the World Model as an argument in addition to the interpreter. */
    NextFactAction(final Variable v, final Relation r, final WorldModelTable pWorldModel) {
        super(r, pWorldModel);
        this.variable = v;
    }


    // Member functions

    public boolean isExecutableAction() { return true; }

    /** Return the next matching WM relation. */
    public Result execute(final Binding b, final Goal currentGoal) {
        WorldModelRelationIterator wmtbe = (WorldModelRelationIterator) this.variable.eval(b).getObject();
        Binding newBinding = new Binding(b);
        newBinding.unbindVariables(this.relation.getArgs());
        WorldModelRelation rel = wmtbe.getNext(newBinding);
        if (rel != null) {
            b.copy(newBinding);
            return Result.SUCCEEDED;
        }
        return Result.FAILED;
    }

    /** Output information to the stream in an in-line manner. */
    public String formattedString(final Binding b) {
        return "NEXTFACT " + this.relation.formattedString(b) + ";";
    }

}

