dofile("../defs/ai_tactics_defs.lua")

local AiTacticsSystem = inherited("AiTacticsSystem", SystemMap)

function AiTacticsSystem:new()
	local ms = instance(self)
	return ms
end

function AiTacticsSystem:wants(ent)
	return ent.aspects.ai_tactics
end

function AiTacticsSystem:ent_added(ent)
	ent.home_x = ent.x
	ent.home_y = ent.y
	ent.home_radius = ent.home_radius or 20
end

function AiTacticsSystem:ent_removed(ent)
end

function AiTacticsSystem:step(dt)
	local world = self.world
	local team_target_system = world:get_system_by_key("team_target")	
	if world then
		for ent, _ in pairs(self.ents) do				
			local ai_target = ent.ai_target
			if ai_target and ai_target.dead then
				ent:set_ai_target(nil)
			end
			if ent.ai_tactics_delay > 0 then
				ent.ai_tactics_delay = ent.ai_tactics_delay - dt
			elseif ent.tactics_template then
				local tdef = AI_TACTICS_TEMPLATES[ent.tactics_template]
				local list = tdef.list
				local picked = list[math.random(1,#list)]
				ent:set_ai_tactics(picked)
				ent.ai_tactics_delay = (tdef.min_delay + math.random()*(tdef.max_delay - tdef.min_delay))
			end

			if ent.ai_tactics then
				local pdef = AI_TACTICS[ent.ai_tactics]
				pdef.step(ent, ent.old_target, dt)
			end
		end
	end
end

return AiTacticsSystem