-- TEMPLATE MISSION SCRIPT : WAVES --
-- Sequentially activates spawn groups until they've all gone, then activates the gate.

function init()
	--sets the default music of the stage
	stage.setMusic("music_mission1.ogg")
	
	--start the player at the correct waypoint
	stage.waypointStart = 0
	
	--track all created ships of this faction
	stage.trackFaction = 3
	
	--loads the map
	stage.loadMap("asteroidbelt")
	
	--starting messages
	stage.newMessage("FLY PILOT AND BECOME LEAF ON THE WIND", "stolenrobot")
	stage.newShakyText("DEFEAT ALL WAVES")
	
	--deactivate the gate
	stage.terrain_get("gate")
	terrain.vars.set("available", 0)
	
	--track if we've won
	stage.vars.set("stagewon", 0)
	
	--track the current enemy wave
	stage.vars.set("wave", 0)
end

function update()
	--soft springy borders
	stage.borders()
	
	--periodically check if we've won
	if stage.vars.get("stagewon") == 0 and stage.scriptTimerTick("check", 2000) == 1 then
		--if most enemies are dead
		if stage.factionCount(3) <= 0 then
			--if there are still things to spawn
			if stage.respawnsStillActive() == 1 then
				--activate the next wave group
				stage.activateSpawnGroup(stage.vars.get("wave"), 1)
				--count up the wave counter
				stage.vars.set("wave", stage.vars.get("wave") + 1)
				
			--if all waves have spawned, there's nothing left
			else
				--victory music!
				stage.setMusic("music_mission3.ogg")
				--activate the gate
				stage.terrain_get("gate")
				terrain.vars.set("available", 1)
				--woo we won
				stage.vars.set("stagewon", 1) 
			end
		end
	end
	
	--you are a disappointment to everybody
	if stage.failure == 1 then
		stage.playDeathMessages()
	--wooo you are a winner
	elseif stage.vars.get("stagewon") == 1 then
		if stage.scriptTimerTick("gatereminder", 10000) == 1 then
			stage.newMessage("GATE IS ACTIVE", "stolenrobot")
		end
	end

	--revive dead players at random waypoint
	--stage.reviveDeadPlayers(math.random(0,(stage.waypoint_count()-1)))
end