-- LUALOCALS < ---------------------------------------------------------
local klots, minetest, pairs, string, vector
    = klots, minetest, pairs, string, vector
local string_format
    = string.format
-- LUALOCALS > ---------------------------------------------------------

-- Make the "kill" command reset the current level

minetest.unregister_chatcommand("kill")

minetest.register_chatcommand("kill", {
		description = "Reset the current level",
		func = function(name)
			if not minetest.is_singleplayer() then
				return false, "this command is for singleplayer only"
			end

			local player = minetest.get_player_by_name(name)
			if not player then return false, "invalid player" end

			local ppos = player:get_pos()
			local curlv, curdist
			for _, lvdata in pairs(klots.leveldata) do
				local dist = vector.distance(lvdata.pos, ppos)
				if (not curlv) or dist < curdist then
					curdist = dist
					curlv = lvdata
				end
			end

			local pos = player:get_pos()
			klots.player_control_set(player, "frozen")
			klots.flash_screen(player, "#000000", true)
			minetest.after(0, function()
					minetest.after(0, function()
							local started = minetest.get_us_time()
							minetest.delete_area(curlv.minp, curlv.maxp)
							minetest.log("warning", string_format(
									"resetting map from %s to %s in %0.3fms",
									minetest.pos_to_string(curlv.minp),
									minetest.pos_to_string(curlv.maxp),
									(minetest.get_us_time() - started) / 1000))
							klots.player_teleport(player, pos, curlv.pos)
						end)
				end)
		end
	})
