local sound_gain = 0.005

local function toggle_light(pos, node, play_sound)
	local is_open = ikea.is_open()
	local is_on = minetest.get_item_group(node.name, "ikea_light") == 1
	local swap_node = minetest.registered_nodes[node.name].ikea_light_swap_node or "air"

	if is_on ~= is_open then
		minetest.swap_node(pos, {name = swap_node, param2 = node.param2})
		if play_sound then
			minetest.sound_play({name = "ikea_light_toggle", pos = pos, max_hear_distance = 150, gain = sound_gain, pitch = 1.0})
		end
	end
end

-- Toggle the lights around the player with sound
minetest.register_abm({
	nodenames = {"group:ikea_light"},
	interval = 1.00,
	chance = 2,
	catch_up = false,
	action = function(pos, node, active_object_count, active_object_count_wider)
		toggle_light(pos, node, true)
	end,
})

-- Toggle the lights loaded in without sound
minetest.register_lbm({
	label = "Light Updater LBM",
	name = "ikea:light_toggle",
	nodenames = {"group:ikea_light"},
	run_at_every_load = true,

	action = function(pos, node)
		toggle_light(pos, node, false)
	end,
})

