-- LUALOCALS < ---------------------------------------------------------
local minetest, pairs, piredo_api, piredo_player, vector
    = minetest, pairs, piredo_api, piredo_player, vector
-- LUALOCALS > ---------------------------------------------------------

local api = piredo_api.get_mod_api()

for suff in pairs({[""] = 1, ["1"] = 1, ["2"] = 1}) do
	piredo_api.add_groups("piredo_terrain:piranesi__crownblock" .. suff, "crown")
	minetest.override_item("piredo_terrain:piranesi__crownblock" .. suff, {
			on_construct = function(pos)
				-- Crowns on nearby thrones
				local found = minetest.find_nodes_in_area(
					vector.subtract(pos, vector.new(16, 0, 16)),
					vector.add(pos, vector.new(16, 0, 16)),
				"group:crown")
				if #found ~= 3 then return end

				-- Put one crown on each throne, reject if any
				-- 2 crowns are too close
				for i = 1, #found - 1 do
					for j = i + 1, #found do
						if vector.distance(found[i], found[j]) < 4 then return end
					end
				end

				-- Remove all crowns
				for i = 1, #found do
					minetest.remove_node(found[i])
					api.magic(found[i], true)
				end

				piredo_player.discover("solve:crowns")
				minetest.set_node(pos, {
						name = "piredo_terrain:piranesi__chess_totem"
					})
			end
		})
end
