-- LUALOCALS < ---------------------------------------------------------
local ipairs, minetest, piredo_api
    = ipairs, minetest, piredo_api
-- LUALOCALS > ---------------------------------------------------------

local api = piredo_api.get_mod_api()
local modstore = minetest.get_mod_storage()

local stopkey = "timer_stopped"
local stopped = modstore:get_string(stopkey) ~= ""

local timerkey = "total_elapsed"
local timer = modstore:get_float(timerkey)
api.timer = timer

local sessionkey = "total_sessions"
local sessions = modstore:get_float(sessionkey)
api.sessions = sessions

function api.stop_timer()
	stopped = true
	modstore:set_string(stopkey, "1")
end

function api.is_timer_stopped() return stopped end

local huds = {}

local function updatehuds()
	local text = minetest.settings:get_bool("piranesi_timer") and (not stopped)
	and api.timefmt(api.timer) or ""

	for _, player in ipairs(minetest.get_connected_players()) do
		local pname = player:get_player_name()
		local hud = huds[pname]
		if not hud then
			hud = {
				id = player:hud_add({
						[piredo_api.hudtype] = "text",
						position = {x = 1, y = 0},
						alignment = {x = -1, y = 1},
						offset = {x = -4, y = 4},
						text = text,
						number = 0xffffffff,
						style = 5,
						z_index = 1100
					}),
				text = text,
			}
			huds[pname] = hud
		end
		if hud.text ~= text then
			player:hud_change(hud.id, "text", text)
			hud.text = text
		end
	end
end
minetest.register_on_leaveplayer(function(player)
		huds[player:get_player_name()] = nil
	end)

local lasttime
minetest.register_globalstep(function()
		local now = minetest.get_us_time() / 1000000
		if lasttime and not stopped then
			timer = timer + now - lasttime
			modstore:set_float(timerkey, timer)
		end
		lasttime = now
		api.timer = timer
		updatehuds()
	end)

minetest.register_on_joinplayer(function(player)
		updatehuds()
		if stopped then return end
		local pname = player:get_player_name()
		local _, mname = api.mainplayer()
		if pname ~= mname then return end
		sessions = sessions + 1
		modstore:set_float(sessionkey, sessions)
		api.sessions = sessions
	end)
