-- Dust Particles --
minetest.register_abm({
	nodenames = {"group:ikea_fx_dust"},
	interval = 4.00,
	chance = 1,
	catch_up = false,
	action = function(pos, node, active_object_count, active_object_count_wider)
		local spawner_chance = minetest.registered_nodes[node.name].ikea_fx_dust_spawner_chance
		if math.random(spawner_chance) ~= 1 then
			return
		end

		local amount = minetest.registered_nodes[node.name].ikea_fx_dust_amount
		local height = pos.y / 5
		local center_y = (math.random()) * (pos.y - 1)
		local width = (1 - (center_y / pos.y)) * 5
		local radius = width / 2

		minetest.add_particlespawner({
			amount = amount,
			time = 4,
			minpos = {x = pos.x - radius, y = center_y - (height / 2), z = pos.z - radius},
			maxpos = {x = pos.x + radius, y = center_y + (height / 2), z = pos.z + radius},
			minvel = {x = 0.05, y = 0.00, z = 0.05},
			maxvel = {x = 0.1, y = 0.01, z = 0.01},
			minacc = {x = 0, y = 0, z = 0},
			maxacc = {x = 0, y = 0, z = 0},
			minexptime = 8,
			maxexptime = 32,
			minsize = 0.1,
			maxsize = 0.3,
			collisiondetection = true,
			collision_removal = true,
			object_collision = true,
			vertical = false,
			texture = "ikea_fx_dust.png",
			glow = 5,
		})
	end,
})

-- Light Toggling --
local light_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 = light_sound_gain,
				pitch = 1.0,
			})
		end
		local timer = minetest.get_node_timer(pos)
		local rate = minetest.registered_nodes[swap_node].ikea_fx_dust_spawn_rate
		if timer and rate then
			timer:start(rate)
		end
	end
end

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 the lights around the player with sound
		toggle_light(pos, node, true)
	end,
})

minetest.register_lbm({
	label = "Light Updater LBM",
	name = "ikea_fx:light_toggle",
	nodenames = {"group:ikea_light"},
	run_at_every_load = true,

	action = function(pos, node)
		-- Toggle the lights loaded in without sound
		toggle_light(pos, node, false)
	end,
})

