-- manages sending out enemies

WaveController = class(Group, function(o, waveData, enemies, parent)
	Group.init(o)
	o.waveData = waveData
	o.enemies = enemies
	o.parent = parent
	o.waveOn = true
	o.wavesStarted = false
	o.waveCount = 0
	o.toSpawn = {}
	o.display = o:add(StringObject(0,0,"REST", "_santa_fe_30"))
	o.display:setScrollFactor(Vec2(0,0))
	-- this is a default before the waves get setup
	o.thisWaveSyncRate = 1
	o.syncRate = o.thisWaveSyncRate
end)
function WaveController:startWaves()
	self.wavesStarted = true
	self:setupNextWave()
end
function WaveController:setupNextWave()
	self.waveCount = self.waveCount+1
	if self.waveCount <= #self.waveData then
		self.nextWave = self.waveData[self.waveCount].time
		-- loop through the enemies, and file them in the to spawn
		local spawnTotal = 0
		for i,v in ipairs(self.waveData[self.waveCount].enemies) do
			if self.toSpawn[v.t] then
				self.toSpawn[v.t] = self.toSpawn[v.t] + v.count
			else
				self.toSpawn[v.t] = v.count
			end
			spawnTotal = spawnTotal+v.count
		end
		if spawnTotal > 0 then
			self.thisWaveSyncRate = self.waveData[self.waveCount].time/spawnTotal
		else
			self.thisWaveSyncRate = 1
		end
		self.syncRate = 0
	else
		self.waveOn = false
	end
end
function WaveController:update()
	Group.update(self)
	self.syncRate = self.syncRate - bludG.elapsed
	if self.syncRate <= 0 then
		self:sync()
		print(self.thisWaveSyncRate)
		self.syncRate = self.thisWaveSyncRate
	end
	if self.wavesStarted and (self.waveOn or self:doesSpawnRemain()) then
		self.display:setValue("NEXT WAVE: "..string.format("%.2f", self.nextWave))
		self.display:setColor(40, 100, 240)
		self.nextWave = self.nextWave - bludG.elapsed
		if self.nextWave <= 0 then
			self:setupNextWave()
		end
	else
		-- don't do anything
	end
	self.display:setPosition(bludG.camera.w-self.display.w, 0)
end
function WaveController:setOver()
	return not self.waveOn and not self:doesSpawnRemain()
end
function WaveController:doesSpawnRemain()
	local spawnRemain = 0
	for k,v in pairs(self.toSpawn) do
		if v > 0 then
			spawnRemain = spawnRemain+v
		end
	end
	if spawnRemain == 0 then return false end
	return spawnRemain
end
function WaveController:sync()
  local spawnEnum = {}
  for k,v in pairs(self.toSpawn) do
  	if v then
  		table.insert(spawnEnum, {t=k, c=v})
  	end
  end
  if self.wavesStarted and (self.waveOn or self:doesSpawnRemain()) then
  	-- always spawn on a sync if we can
	  	local e = spawnEnum[math.random(#spawnEnum)]
	  	if e.c > 0 then
	    	self:addEnemyOffscreen(_G[e.t])
	    	self.toSpawn[e.t] = e.c-1
	    end
  end
end

function WaveController:addEnemyOffscreen(t)
	self.enemies:add(t(0, bludG.camera.h/2, self.parent))
end

-- mainState = WrapperState(Group());
-- ps = PlayState()
-- mainState:changeState(ps)
