--[[ 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
--]]


local modname = core.get_current_modname()
local S = core.get_translator(modname)

local huds = {}


local function add_overlay(player, hp)
	local props = player:get_properties()
	local max = props.hp_max
	local name = player:get_player_name()
	local level = math.floor((max - hp) * 100 / max)

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

	local oldhud = huds[name]

	if oldhud then
		player:hud_change(oldhud, "text", "thinkingwitharrows_healthoverlay_overlay.png^[opacity:" .. level)
	else
		huds[name] = player:hud_add {
			[hud_type] = "image",
			alignment = {x = 1, y = 1},
			z_index = 1001,
			scale = {x = -100, y = -100}, -- fullscreen
			text = "thinkingwitharrows_healthoverlay_overlay.png^[opacity:" .. level,
		}
	end
end


core.register_on_player_hpchange(function(player, hp_change, reason)
	local hp = player:get_hp()
	add_overlay(player, hp + hp_change)
end)


core.register_on_respawnplayer(function(player)
	local name = player:get_player_name()

	if huds[name] then
		player:hud_remove(huds[name])
		huds[name] = nil
	end
end)
