-- LUALOCALS < ---------------------------------------------------------
local ipairs, math, minetest, pairs, piredo_api, piredo_schems, string
    = ipairs, math, minetest, pairs, piredo_api, piredo_schems, string
local math_ceil, math_floor, string_format
    = math.ceil, math.floor, string.format
-- LUALOCALS > ---------------------------------------------------------

local modname = minetest.get_current_modname()
local api = piredo_api.get_mod_api()

local formname = modname .. "_forceroom"

local roomform
do
	local rooms = {}
	local function addrooms(prefix)
		for _, k in ipairs(api.find_schematics(prefix)) do
			local v = piredo_schems[k]
			local d = (v.internal_name or v.title or k)
			d = minetest.formspec_escape(d)
			rooms[#rooms + 1] = {k = k, d = d}
		end
	end
	addrooms("normal")
	addrooms("large")
	addrooms("quad_hall")
	addrooms("special_candle")
	addrooms("special_final")
	addrooms("mystery")
	local btnw = 8
	local height = math_floor((#rooms) ^ 0.5 * (btnw ^ 0.5))
	local width = math_ceil((#rooms) / height)
	roomform = string_format("size[%f,%f]", width * btnw, height * 0.75)
	local x, y = 0, 0
	for _, room in ipairs(rooms) do
		roomform = string_format("%sbutton[%f,%f;%f,%f;%s;%s]",
			roomform, x, y, btnw, 1, room.k, room.d)
		y = y + 0.75
		if y >= height * 0.75 then y = 0 x = x + btnw end
	end
end

minetest.register_chatcommand("room", {
		description = "force next room",
		privs = {give = true},
		func = function(pname)
			return minetest.show_formspec(pname, formname, roomform)
		end
	})

minetest.register_on_player_receive_fields(function(player, fname, fields)
		if fname ~= formname or not minetest.check_player_privs(player, "give")
		then return end

		local room
		for k in pairs(piredo_schems) do
			if fields[k] then
				room = k
				break
			end
		end
		if not room then return end

		api.statedb.forced = room
		api.savedb()

		minetest.close_formspec(player:get_player_name(), formname)
		minetest.chat_send_player(player:get_player_name(),
			string_format("next room = %s (%s)", room, fields[room]))
	end)
