package at.oefai.aaa.agent.jam;

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

/**
 * Represents the runtime state of sequence constructs.
 * @author Marc Huber
 * @author Jaeho Lee
 */

class PlanRuntimeSequenceState implements PlanRuntimeState {

    private PlanSequenceConstruct thisConstruct = null;
    private PlanRuntimeState substate = null;

    private int currentConstructNum = 0;

    /**  */
    PlanRuntimeSequenceState(final PlanSequenceConstruct be) {
        this.thisConstruct = be;
    }

    // Member functions

    /**  */
    public State execute(final Binding b, final Goal thisGoal) {
        if (this.substate == null) {
            if (this.thisConstruct.getNumConstructs() < 1) {
                return State.CONSTRUCT_COMPLETE; // empty sequence = SUCCEED
            }
            this.substate = this.thisConstruct.getConstruct(0).newRuntimeState();
        }
        State returnVal = this.substate.execute(b, thisGoal);
        if (returnVal == State.CONSTRUCT_FAILED) {
            // The substate failed, so get rid of it
            this.substate = null;
            return State.CONSTRUCT_FAILED;
        } else if (returnVal == State.CONSTRUCT_COMPLETE) {
            // Check to see if the sequence is finished
            if (this.currentConstructNum >= this.thisConstruct.getNumConstructs() - 1) {
                // The substate's done, so first get rid of it
                this.substate = null;
                return State.CONSTRUCT_COMPLETE;
            }
            // Not done yet, so go on to the next action
            this.substate = this.thisConstruct.getConstruct(++this.currentConstructNum).newRuntimeState();
            return State.CONSTRUCT_INCOMP;
        } else {
            return State.CONSTRUCT_INCOMP;
        }
    }

}

