-- LUALOCALS < ---------------------------------------------------------
local get_mod_api, math, minetest, vector
    = get_mod_api, math, minetest, vector
local math_acos, math_cos, math_pi, math_random, math_sin
    = math.acos, math.cos, math.pi, math.random, math.sin
-- LUALOCALS > ---------------------------------------------------------

local api = get_mod_api()
local modname = minetest.get_current_modname()

local function play(pname, pos, ppos)
	local dist = vector.distance(pos, ppos)
	return minetest.sound_play(modname .. "_air",
		{
			to_player = pname,
			pos = pos,
			gain = 0.00015 * dist,
			pitch = 0.8 + math_random() * 0.4
		})
end

local waittimes = {}
api.register_playerstep(function(player, dtime, pname)
		if api.is_endcredits() then return end

		waittimes[pname] = (waittimes[pname] or 0) - dtime
		if waittimes[pname] > 0 then return end
		waittimes[pname] = math_random()

		local pos = player:get_pos()
		pos.y = pos.y + player:get_properties().eye_height

		local l = math_acos(2 * math_random() - 1) - math_pi / 2
		local t = math_pi * 2 * math_random()
		local target = {
			x = pos.x + math_cos(l) * math_sin(t) * 8,
			y = pos.y + math_sin(l) * 8,
			z = pos.z + math_cos(l) * math_cos(t) * 8
		}

		for pt in minetest.raycast(pos, target, false, true) do
			if pt.type == "node" then
				return play(pname, pt.intersection_point or pt.above, pos)
			end
		end
		return play(pname, target, pos)
	end)

minetest.register_on_joinplayer(function(player)
		local id = minetest.sound_play(modname .. "_noise", {
				to_player = player:get_player_name(),
				loop = true,
				gain = 0.00000001
			})
		minetest.sound_fade(id, 0.0001, 0.0005)
	end)
