package at.oefai.aaa.agent.jam;

import java.io.Serializable;

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

/**
 * A built-in JAM primitive action for binding plan variables with world model entries.
 * This is similar to a FactAction, but passed-in variables bindings are NOT used for matching.
 * Rather, the variables are overwritten with data from the
 * world model whenever any world model entry exists with the given name.
 * @author Marc Huber
 * @author Jaeho Lee
 */
class RetrieveAction extends WorldModelAction implements Serializable {

    /** Constructor w/ relation to retrieve from the World Model as an argument in addition to the interpreter. */
    RetrieveAction(final Relation pRelation, final WorldModelTable pWorldModel) {
        super(pRelation, pWorldModel);
    }


    // Member functions

    public boolean isExecutableAction() { return true; }

    /** Retrieve the relation from the World Model. */
    public Result execute(final Binding b, final Goal currentGoal) {
        // unbound variables before matching
        if (b != null) {
            b.unbindVariables(this.relation.getArgs());
        }
        // now try match to get new values
        return this.worldModel.match(this.relation, b) ? Result.SUCCEEDED : Result.FAILED;
    }


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

}

