local AiInputSystem = inherited("AiInputSystem", SystemMap)

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

function AiInputSystem:wants(ent)
	return ent.aspects.ai_input
end

function AiInputSystem:ent_added(ent)	
end

function AiInputSystem:ent_removed(ent)
end

function AiInputSystem: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 dist = math.min(1,math.distance(0,0,dx,dy))
			local thrust_angle = math.angleBetweenPoints(0,0,dx,dy)
			
			]]
			
			if ent.desired_amount then
				ent:set_input_vector(ent.desired_angle, ent.desired_amount)
				ent.desired_amount = nil
			else
				ent:set_input_vector(ent.desired_angle, 0)
			end

			if ent.desired_flip ~= nil then
				ent:set_flip(ent.desired_flip)
				ent.desired_flip = nil
			end

			local ai_target = ent.ai_target
			if ai_target then
				local ang = math.angleBetweenPoints(ent.x, ent.y, ai_target.x, ai_target.y)
				ent:set_look_angle(ang)				
				if ent.aspects.attack then
					local dist = math.distance(ent.x, ent.y, ai_target.x, ai_target.y)-(ai_target.radius or 0)
					local best_slot = ent:get_in_range_attack_slot(dist)
					--print("slot", best_slot, dist)
					if ent.ai_best_attack_slot ~= best_slot then
						local old = ent.ai_best_attack_slot
						if old then
							ent:set_attack_intent(old, false)
						end
						ent.ai_best_attack_slot = best_slot
						if best_slot then
							--print("slot", best_slot, "go")
							ent:set_attack_intent(best_slot, true)						
						end
					end
				end
			else
				local old = ent.ai_best_attack_slot
				if old then
					ent:set_attack_intent(old, false)
					ent.ai_best_attack_slot = nil
				end
			end
			--looking
			--[[
			local cx, cy = cursor.camera_x, cursor.camera_y
			local look_angle = math.angleBetweenPoints(ent.x,ent.y,cx,cy)
			ent:set_look_angle(look_angle)
			]]		
			--ent:set_action_intent("primary",nil)
			--ent:set_action_intent("secondary",nil)
			--
			--ent:set_action_intent("primary", "melee")	
			--ent:set_action_intent("secondary", "ranged")	
		end
	end
end

return AiInputSystem