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

function klots.level_reset(lv)
	local lvdata = klots.leveldata[lv] or error("invalid level")

	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 mapblocks 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
end
