--[[
	
	Detects if an enemy is close by and if the agent can see the enemy.
	
	This will return the currently selected target if one is present
]]


function AngleBetweenVectors(a, b)
    return math.acos(a:Dot(b) / (a.Magnitude * b.Magnitude))
end

return function( self )
	
	--local Target = self.Target
	local ClosestCharacter = nil
	local ClosestDistance = self.MaxDetectionRange
	--if not Target then
		for _,plr in pairs(game.Players:GetPlayers()) do
			if plr.Character and plr.Character:FindFirstChild("HumanoidRootPart") then
				local dist = (plr.Character.HumanoidRootPart.Position - self.HumanoidRootPart.Position).magnitude

				--[[print("Dot:",self.HumanoidRootPart.CFrame.lookVector:Dot(
						plr.Character.HumanoidRootPart.Position 
						- self.HumanoidRootPart.Position))]]

				if dist < ClosestDistance 
					and -- Get the dot product to see if the NPC can see the player
					--[[self.HumanoidRootPart.CFrame.lookVector:Dot(
						plr.Character.HumanoidRootPart.Position 
						- self.HumanoidRootPart.Position) > (self.MaxDetectionAngle/360)]]
						math.deg(AngleBetweenVectors(self.HumanoidRootPart.CFrame.lookVector, plr.Character.HumanoidRootPart.Position
		- self.HumanoidRootPart.Position)) <= self.MaxDetectionAngle/2
					then
					ClosestDistance = dist
					ClosestCharacter = plr.Character
				end
			end
		end
	--end


	self.ClosestEnemy = ClosestCharacter
	if self.ClosestEnemy then
		--print("EnemyIsNearby,",true)
		--print("Closest Character:",self.ClosestEnemy.Name)
		self:AddAggro( self.ClosestEnemy,.0000001 ) -- we're adding a tiny aggro amount so that damages will take priority
		return true
	else
		--print("EnemyIsNearby,",false)
		return false
	end
end
