package at.oefai.aaa.agent.jam;

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

/**
 * Represents the runtime state of plan constructs.
 * @author Marc Huber
 * @author Jaeho Lee
 */
class PlanRuntimeWhenState implements PlanRuntimeState {

    private PlanConstruct thisConstruct = null;
    private PlanRuntimeState substate = null;

    private boolean testEvaluated;

    /**  */
    PlanRuntimeWhenState(final PlanWhenConstruct be) {
        this.thisConstruct = be;
        this.substate = be.getSequence().newRuntimeState();
        this.testEvaluated = false;
    }

    //
    // Member functions
    //

    /**  */
    public State execute(final Binding b, final Goal thisGoal) {
        // If we're at the beginning of the construct, then we need to evaluate
        // the test.  If the test fails, we're simply done.  If it succeeds, we
        // go on and execute the sequence of constructs.
        if (! this.testEvaluated) {

            Action.Result testReturnVal = ((PlanWhenConstruct) this.thisConstruct).getTest().execute(b, thisGoal);

            if (testReturnVal != Action.Result.SUCCEEDED) {
                return State.CONSTRUCT_COMPLETE;
            }
            this.testEvaluated = true;
        }

        return this.substate.execute(b, thisGoal);
    }

}

