package meyermike.script.step 
{
    import meyermike.script.Step;
    
    /**
     * Step to loop a bunch of other steps N times
     * @author Mike Meyer
     */
    public class Loop extends Step
    {
        private var mNumLoops:Number;
        private var mLoopsLeft:Number;
        private var mSteps:/*Step*/Array;
        private var mPrevStep:Number;
        private var mNextStep:Number;
        
        public function Loop(numLoops:Number, steps:Array)
        {
            mNextStep = 0;
            mPrevStep = -1;
            mNumLoops = numLoops;
            mLoopsLeft = numLoops;
            mSteps = steps.concat(); // make a copy
        }
        
        /**
         * Play the next step in the loop
         */
        public override function Execute():Boolean
        {
            // early out on empty steplists
            if (0 == mSteps.length)
            {
                return true;
            }
            
            if (mLoopsLeft > 0)
            {
                var beataction:Step = mSteps[mNextStep];
                
                // if it is the first time we are running 
                // it this loop, then we need to make sure 
                // it loses any state information from the 
                // last time through
                if (mPrevStep != mNextStep)
                {
                    beataction.Restart();
                }
                
                if (beataction.Execute())
                {
                    ++mNextStep;
                }
                
                mPrevStep = mNextStep;
                
                if (mNextStep >= mSteps.length)
                {
                    mPrevStep = -1;
                    mNextStep = 0;
                    --mLoopsLeft;
                }
            }
            
            return mLoopsLeft <= 0;
        }
        
        
        /**
         * clear out any state information the step might be saving and 
         * go back to like when it was first created
         */
        public override function Restart():void
        {
            for (var i:Number = 0; i < mSteps.length; ++i)
            {
                mSteps[i].Restart();
            }
            
            mLoopsLeft = mNumLoops;
            mNextStep = 0;
        }
    }
    
}