-- LUALOCALS < ---------------------------------------------------------
local addgroups, get_mod_api, minetest, pairs, piredo_map,
      piredo_player, vector
    = addgroups, get_mod_api, minetest, pairs, piredo_map,
      piredo_player, vector
-- LUALOCALS > ---------------------------------------------------------

local api = get_mod_api()
local modstore = minetest.get_mod_storage()
local key = "candlesequence"

local radius = vector.new(16, 0, 16)
local function puzzlecheck(pos)
	local minp = vector.subtract(pos, radius)
	local maxp = vector.add(pos, radius)
	if #minetest.find_nodes_in_area(minp, maxp, "group:candle_unlit") > 0 then return end

	local found = minetest.find_nodes_in_area(minp, maxp, "piredo_terrain:piranesi__candle")
	if #found < 1 then return end

	if modstore:get_string(key) ~= "12345678" then
		modstore:set_string(key, "")
		for _, p in pairs(found) do
			local id = minetest.get_meta(p):get_int("candle")
			if id > 0 then
				minetest.set_node(p, {
						name = "piredo_terrain:piranesi__candle_unlit" .. id
					})
				minetest.add_particlespawner({
						amount = 10,
						time = 0.05,
						pos = p,
						radius = {min = 0, max = 0.5},
						acc = {x = 0, y = 3, z = 0},
						exptime = {min = 1, max = 3},
						size = {min = 0.5, max = 2},
						glow = 10,
						texture = "default_item_smoke.png^[opacity:64",
					})
			end
		end
		return
	end

	piredo_player.discover("solve:candles")

	local v = vector.new()
	for _, p in pairs(found) do
		v = vector.add(v, p)
	end
	v = vector.round(vector.multiply(v, 1 / #found))

	api.magic(v, true)
	minetest.set_node(v, {
			name = "piredo_terrain:piranesi__neck_totem",
			param2 = 1
		})
end

for i = 1, 8 do
	addgroups("piredo_terrain:piranesi__candle_unlit" .. i, "candle_unlit")
	minetest.override_item("piredo_terrain:piranesi__candle_unlit" .. i, {
			pointable = true,
			on_apply_lighter = function(pos, node)
				minetest.sound_play("default_dug_node", {gain = 0.2, pos = pos}, true)
				node.name = "piredo_terrain:piranesi__candle"
				minetest.swap_node(pos, node)
				minetest.get_meta(pos):set_int("candle", i)
				piredo_map.savechange(pos, node, "candle meta")
				modstore:set_string(key, modstore:get_string(key) .. i)
				puzzlecheck(pos)
			end
		})
end

minetest.override_item("piredo_terrain:piranesi__candle", {
		pointable = false,
		walkable = false
	})
