--------------------------------------------------------------------------------
-- Jorge Eremiev - May 8, 2008
--
-- Particle system used in the stations
--------------------------------------------------------------------------------

--[[ INITIALIZATION PHASE ]] 

-- Create our custom variables
pVelocity = Allocate(2); 
pAge = Allocate(1);

if not initialColor then
   initialColor = Color(1, 1, 1, 0.7); 
end

if not finalColor then
   finalColor = Color(1, 1, 1, 0);
end

if not acceleration then
   acceleration = Vec2(0, 0)
end

lifetime = 400;

initialTime = 2 * (lifetime * 0.1);
fadeTime = 5 * (lifetime * 0.1);
deathTime = 3 * (lifetime * 0.1);

-- Set the particles texture
SetTexture("working_particle");
SetBlendMode(kBlendNormal);

-- The maximun number of particles available
SetNumParticles(15);

--[[ ACTION PHASE ]]

-- Give initial values to some of the variables
fScale = 0.3;
pScale:Init(0.8);
pPosition:Init(fRange(Vec2(-15, -5), Vec2(30, 5)));
pVelocity:Init(fRange(Vec2(-10, -20), Vec2(10, -40)));

-- Update the particles velocity and position
pPosition:Anim(pPosition + fTimeScale(pVelocity));

-- Update the particles age
pAge:Anim(pAge + fAge());

-- Set the particles color according to its age
pColor:Anim(fFade(pAge, finalColor, initialTime, initialColor, fadeTime, initialColor, deathTime, finalColor));

-- Make the particle bigger
pScale:Anim(pScale + fTimeScale(0.8));

-- Kill the particle if it's too old
Anim(fExpire(fGreater(pAge, lifetime)));

-- This variable must be changed from C++, when the worker starts working
gActive = true;

-- This variable must be changed from C++, when the worker is donde
continueWave = true;

-- Timer that will tells us for how long to create particles
local waveTimer;
createWaveTimer = true;

-- Timer that will keep track of the time we have to wait, before the new wave
-- of particles begin
local waitTimer;

-- Define the Update function
function Update(seconds)

   if gActive then
   
       -- Start creating particles
      CreateParticles(seconds * 30);
      
      -- Start the timer that will tells us when to stop creating particles
      --if createWaveTimer then
         --waveTimer = NewTimeout(0.5)
             --createWaveTimer = false
          --end
      
      -- If enough time has passed, stop creating particles, and start the
      -- timer that will tell us how much time we have to wait, before the
      -- new wave of particles begins   
      if waveTimer then
            if waveTimer(seconds) then
              gActive = false
                waitTimer = NewTimeout(0.9)
             end
      end
    else   
      -- If enough time has passed, begin the new wave of particles
      if continueWave then
         if waitTimer then
            if waitTimer(seconds) then
               gActive = true
                   createWaveTimer = true
                end
             end
      end                           
   end
end