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.ExpList;
import at.oefai.aaa.agent.jam.types.Value;

/**
 * A simple (non-decomposable) action within a plan.
 * @author Marc Huber
 * @author Jaeho Lee
 */
class SimpleAction extends AbstractAction implements Serializable {

    private final String name;
    private final ExpList args;
    private final Interpreter interpreter;


    /** Constructor with name and argument list. */
    SimpleAction(final String pName, final ExpList el, final Interpreter pInterpreter) {
        this.name = pName;
        this.args = el;
        this.interpreter = pInterpreter;
    }

    // Member functions

    public boolean isExecutableAction() {
        return true;
    }

    public ExpList getArgs() {
        return this.args;
    }

    /** Execute a non-decomposable action. */
    public Result execute(final Binding b, final Goal currentGoal) {
        Value returnValue;
        returnValue = this.interpreter.getSystemFunctions().execute(this.name, this.args, b, currentGoal);
        if (returnValue.isDefined()) {
            return (returnValue.eval(b).isTrue()) ? Result.SUCCEEDED : Result.FAILED;
        }
        returnValue = this.interpreter.getUserFunctions().execute(this.name, this.args, b, currentGoal);
        if (returnValue.isDefined()) {
            return (returnValue.eval(b).isTrue()) ? Result.SUCCEEDED : Result.FAILED;
        }
        // log.info("SimpleAction: Action \"" + _name +
        //          "\" not found in user-defined functions in UserFunctions.java!\n");
        return Result.FAILED;
    }

    /** Print out the action information in-line with other information. */
    public String formattedString(final Binding b) {
        return "PRIMITIVE: " + this.name + " " + this.args.formattedString(b) + " ";
    }

    public String getName() {
        return this.name;
    }
}
