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

local getdata

local function speedrunstep(player, data, dtime)
	local pos = player:get_pos()
	if data.starting then
		if pos.y >= 10000 then return end
		data.starting = nil
		data.running = 0
	elseif data.running then
		if pos.y >= 10000 then
			data.final = data.running
			data.running = nil
		else
			data.running = data.running + dtime
		end
	elseif data.final then
		if pos.y < 10000 then data.final = nil end
	else
		return
	end

	local text = string_format("%0.3f", data.final or data.running)

	if data.hud then
		if data.text ~= text then
			player:hud_change(data.hud, "text", text)
			data.text = text
		end
	else
		data.text = text
		data.hud = player:hud_add({
				hud_elem_type = "text",
				position = {x = 1, y = 0},
				text = text,
				alignment = {x = -1, y = 1},
				number = 0xFFFF00,
				offset = {x = -8, y = 8}
			})
	end
end

minetest.register_chatcommand("speedrun", {
		description = "Reset world and time a run through the whole game",
		privs = {server = true},
		func = function(name)
			if not getdata then
				getdata = klots.register_playerstep(speedrunstep)
			end
			for k in pairs(klots.leveldata) do
				klots.level_reset(k)
			end
			minetest.registered_chatcommands.lv.func(name, "1")
			getdata(name).starting = true
		end
	})
