-- LUALOCALS < ---------------------------------------------------------
local get_mod_api, minetest, pairs, piredo_items, posrel
    = get_mod_api, minetest, pairs, piredo_items, posrel
-- LUALOCALS > ---------------------------------------------------------

local api = get_mod_api()

-- white flowerpot param2:
-- 0 = decoration only
-- 1 = removable flowers
-- 2 = removable, plus the direction hint

local flowertypes = {
	chrysanthemum_green = false,
	dandelion_white = true,
	dandelion_yellow = false,
	geranium = false,
	rose = false,
}

local function checkwhite(pos)
	for k, v in pairs(flowertypes) do
		if not (v or minetest.find_node_near(pos, 2,
				"piredo_terrain:flowerpot__flowers_" .. k)) then
			return
		end
	end
	return true
end

local emptydef = {}
for name, white in pairs(flowertypes) do
	emptydef["on_apply_" .. name] = function(pos, node)
		node.name = "piredo_terrain:flowerpot__flowers_" .. name
		node.param2 = white and (checkwhite(pos) and 2 or 1) or 0
		minetest.swap_node(pos, node)
		if node.param2 == 2 then api.magic(pos, true) end
		return ""
	end
	minetest.override_item("piredo_terrain:flowerpot__flowers_" .. name, {
			on_punch = piredo_items.ratelimit(function(pos, node, player)
					if white and node.param2 < 1 then return end
					local flower = "piredo_terrain:piranesi__" .. name
					piredo_items.pickupeffect(pos, {name = flower})
					player:get_inventory():add_item("main", flower)
					node.name = "piredo_terrain:flowerpot__empty"
					minetest.swap_node(pos, node)
				end)
		})
end

minetest.override_item("piredo_terrain:flowerpot__empty", emptydef)

local function ghostparticles(wait, start, target)
	return minetest.after(wait, function()
			minetest.sound_play("piredo_puzzle_ncziprune_hum",
				{pos = start}, true)
			return minetest.add_particlespawner({
					amount = 100,
					time = 2,
					pos = start,
					radius = {min = 0, max = 1},
					attract = {
						kind = "point",
						origin = target,
						strength = 0.5
					},
					exptime = {min = 1, max = 2},
					size = {min = 1, max = 2},
					glow = 10,
					texture = "piranesi_ghost_particle.png",
				})
		end)
end

local playing
minetest.register_abm({
		nodenames = {"piredo_terrain:flowerpot__flowers_dandelion_white"},
		interval = 1,
		chance = 1,
		action = function(pos, node)
			if node.param2 ~= 2 then return end

			if playing then return end
			playing = true

			local rel = posrel(pos)
			local above = rel(0, 3, 0)
			rel = posrel(above)
			ghostparticles(2, above, rel(0, 0, 5))
			ghostparticles(4, above, rel(5, 0, 0))
			ghostparticles(6, above, rel(-5, 0, 0))
			ghostparticles(8, above, rel(0, 0, 5))
			ghostparticles(10, above, rel(5, 0, 0))
			minetest.after(12, function() playing = nil end)
		end
	})
