-- Artificial intelligence functions

AI = {}

function AI.GetAngle(fx,fy,tx,ty)
	local Angle = math.atan2(fy-ty,fx-tx) - math.pi/2
	if Angle < -math.pi then return Angle + math.pi*2 end
	return Angle
end

function AI.GetDist(fx,fy,tx,ty)
	return math.sqrt((fx-tx)^2 + (fy-ty)^2)
end

-- Detect players in a radius
function AI.DetectPlayers(x,y,radius,alive)
	local t = {}
	for _, id in pairs(player(0,"table")) do
		if AI.GetDist(x, y, player(id,"x"), player(id,"y")) < radius then
			if (alive and player(id,"health") > 0) or not alive then
				table.insert(t, id)
			end
		end
	end
	return t
end

-- Closest player from table
function AI.ClosestPlayer(x,y,tab)
	if not tab then tab = AI.DetectPlayers(x, y, 380) end
	local p, d
	for _, id in pairs(tab) do
		local Dist = AI.GetDist(x, y, player(id,"x"), player(id,"y"))
		if not p or Dist < d then
			p = id
			d = Dist
		end
	end
	return p
end

function AI.MaxLine(fx,fy,tx,ty)
	local Angle = AI.GetAngle(fx,fy,tx,ty)
	local Dist = math.round(AI.GetDist(fx,fy,tx,ty)/8)
	
	for i = 1, Dist*8 do
		local x = fx + math.sin(Angle) * i * 8
		local y = fy - math.cos(Angle) * i * 8
		if not tile(math.floor(x/32), math.floor(y/32), "walkable") then
			return (i-1)*8
		end
	end
	return Dist
end

-- Check free line from two vectors
function AI.Freeline(fx,fy,tx,ty)
	local Angle = AI.GetAngle(fx,fy,tx,ty)
	local Dist = math.round(AI.GetDist(fx,fy,tx,ty)/8)
	
	for i = 1, Dist*8 do
		local x = fx + math.sin(Angle) * i * 8
		local y = fy - math.cos(Angle) * i * 8
		if not tile(math.floor(x/32), math.floor(y/32), "walkable") then
			return false
		end
	end
	return true
end

function AI.ViewArea(fx,fy,tx,ty,a,spread)
	local Angle = math.deg(AI.GetAngle(fx, fy, tx, ty))
	return math.abs(Angle - a) <= aspread or math.abs(Angle - a) >= 360 - aspread
end