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 PlanRuntimeDoState implements PlanRuntimeState {

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

    /**  */
    PlanRuntimeDoState(final PlanDoConstruct be) {
        this.thisConstruct = be;
        this.substate = be.getSequence().newRuntimeState();
    }

    //
    // Member functions
    //

    /**  */
    public State execute(final Binding b, final Goal thisGoal) {
        // Execute the current PLAN constructs in the loop.  If execution
        // reaches the end of the iteration body then check the test condition.
        State returnVal = this.substate.execute(b, thisGoal);

        if (returnVal == State.CONSTRUCT_FAILED) {
            return State.CONSTRUCT_FAILED;
        } else if (returnVal == State.CONSTRUCT_COMPLETE) {
            Action.Result testReturnVal = ((PlanDoConstruct) this.thisConstruct).getTest().execute(b, thisGoal);
            if (testReturnVal != Action.Result.SUCCEEDED) {
                return State.CONSTRUCT_COMPLETE;
            }
            this.substate = ((PlanDoConstruct) this.thisConstruct).getSequence().newRuntimeState();
            return State.CONSTRUCT_INCOMP;
        } else { // return_val == Status.CONSTRUCT_INCOMP) {
            return State.CONSTRUCT_INCOMP;
        }
    }

}

