-- LUALOCALS < ---------------------------------------------------------
local ipairs, klots, minetest, string, tonumber, type
    = ipairs, klots, minetest, string, tonumber, type
local string_format
    = string.format
-- LUALOCALS > ---------------------------------------------------------

function klots.level_reset(lv)
	if type(lv) == "table" and lv.x and lv.y and lv.z then
		lv = klots.level_from_pos(lv)
	end

	if not lv then return end
	if not tonumber(lv) then return end
	local lvdata = klots.leveldata[lv]
	if not lvdata then return end

	local inlv = {}
	for _, player in ipairs(minetest.get_connected_players()) do
		if klots.level_from_pos(player:get_pos()) == lv then
			inlv[#inlv + 1] = player
			klots.player_control_set(player, "frozen")
			klots.flash_screen(player, true)
		end
	end

	local started = minetest.get_us_time()
	local dirty = klots.mapblock_dirty(lvdata.minp, lvdata.maxp)
	for i = 1, #dirty do
		local p = dirty[i]
		minetest.delete_area(p, p)
	end
	minetest.log("warning", string_format(
			"reset %d mapblock(s) from %s to %s in %0.3fms",
			#dirty,
			minetest.pos_to_string(lvdata.minp),
			minetest.pos_to_string(lvdata.maxp),
			(minetest.get_us_time() - started) / 1000))

	for _, player in ipairs(inlv) do
		klots.player_teleport(player, player:get_pos(), lvdata.pos)
	end

	return true
end
