--localize getter for intensity
local get_intensity = mob_spawning_director.get_intensity


local loop_length = 6.0 - 0.1

-- State tracking stuff
local current_level = 0
local current_music = nil
local last_intensity = 0
local last_update_time = 0

local track_name_transit = "mood_music_transit"
local track_name_leveled = "mood_music_level"

local function is_dark()
	local tod = minetest.get_timeofday()
	return tod < 0.2 or tod > 0.8
end



local function update()
	local time = os.time()
	if current_level > 0
	then
		if time < last_update_time + loop_length
		then
			return
		end
	end
	last_update_time = time

	local intensity = get_intensity()
	if not is_dark()
	then
		intensity = intensity * 0.1
	end
	last_intensity = intensity
	intensity = intensity + math.max(0, intensity - last_intensity) * 3

	local il = {0.05, 0.35, 0.6, 0.8}
	local last_level = current_level
	if intensity <= il[1]
	then
		if current_level > 0
		then
			current_level = current_level - 1
		end
	elseif intensity > il[1] and intensity <= il[2]
	then
		if current_level > 1
		then
			current_level = current_level - 1
		elseif current_level < 1
		then
			current_level = current_level + 1
		end
	elseif intensity > il[2] and intensity <= il[3]
	then
		if current_level > 2
		then
			current_level = current_level - 1
		elseif current_level < 2
		then
			current_level = current_level + 1
		end
	elseif intensity > il[3] and intensity <= il[4]
	then
		if current_level > 3
		then
			current_level = current_level - 1
		elseif current_level < 3
		then
			current_level = current_level + 1
		end
	elseif intensity > il[4]
	then
		if current_level < 4
		then
			current_level = current_level + 1
		end
	end

	if last_level ~= current_level
	then
		if defense--.debug
		then
			minetest.chat_send_all("Level: " .. current_level)
		end
		if current_music
		then
			minetest.sound_stop(current_music)
		end
		if current_level > 0
		then
			current_music = minetest.sound_play(track_name_leveled .. current_level, {
				pos = nil,
				gain = 0.2 + current_level * 0.15,
				loop = true,
			})
		end
		if last_level > 0
		then
			minetest.sound_play(track_name_transit, {
				gain = 0.2 + last_level * 0.1
			})
		end
	end
end

minetest.register_globalstep(function(dtime)
	update()
end)
