--[[ init.lua
Copyright 2025 Pixelo789

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

SPDX-License-Identifier: AGPL-3.0-or-later
--]]


thinkingwitharrows_speedruntimer = {}
local modname = core.get_current_modname()
local S = core.get_translator(modname)

local texts = {}
local bgs = {}


function thinkingwitharrows_speedruntimer._add_time(player, text)
	local name = player:get_player_name()
	local meta = player:get_meta()

	local time = meta:get_int("time")
	local color = 0x00FF00
	if time == 0 then
		time = core.get_gametime()
		color = 0xFFFFFF
	end

	if meta:get_int("speedrun_has_cheated") ~= 0 then
		color = 0xFF0000
	end

	player:hud_change(texts[name], "text", thinkingwitharrows.format_time(time))
	player:hud_change(texts[name], "number", color)
end


function thinkingwitharrows_speedruntimer.start_timer(player)
	local name = player:get_player_name()

	-- compatibility with older versions of Luanti
	local hud_type
	if core.features.hud_def_type_field then
		hud_type = "type"
	else
		hud_type = "hud_elem_type"
	end

	-- background
	local oldbg = bgs[name]
	bgs[name] = player:hud_add {
		[hud_type] = "image",
		position = {x = 0, y = 1},
		alignment = {x = 1, y = -1},
		z_index = 2000,
		scale = {x = 36, y = 9},
		text = "thinkingwitharrows_init_black_box.png^[opacity:" .. 50,
	}
	if oldbg then
		player:hud_remove(oldbg)
	end

	-- timer text
	local oldtext = texts[name]
	texts[name] = player:hud_add {
		[hud_type] = "text",
		position = {x = 0, y = 1},
		alignment = {x = 1, y = 0},
		offset = {x = 20, y = -36},
		z_index = 2001,
		scale = {x = 100, y = 100},
		text = "",
		number = 0xFFFFFF,
		size = {x = 2},
	}
	if oldtext then
		player:hud_remove(oldtext)
	end

	core.register_globalstep(function(dtime)
		thinkingwitharrows_speedruntimer._add_time(player)
	end)
end


-- Anti-cheat for speedruns
core.register_on_priv_grant(function(name)
	local player = core.get_player_by_name(name)
	local meta = player:get_meta()

	meta:set_int("speedrun_has_cheated", 1)
end)

core.register_on_cheat(function(player)
	local meta = player:get_meta()

	meta:set_int("speedrun_has_cheated", 1)
end)
