-- Copyright © 2014-2020 4aiman, Hugo Locurcio and contributors
-- Copyyright © 2024 Giov4, Zughy
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

local function scale_to_default_hp() end

-- Localize this functions for better performance,
-- as it's called on every step
local vector_distance = vector.distance
local max = {hp = 20}



function block_league.add_hp_bar(arena, player, joined)
  local p_name = player:get_player_name()
  local teamID = arena.players[p_name].teamID
  local staticdata = {owner = p_name, teamID = teamID}
  local teammates = arena_lib.get_players_in_team(arena, teamID)
  local observers = {}

  for _, pl_name in ipairs(teammates) do
    observers[pl_name] = true

    -- renderizza le barre di chi era già dentro (current_time non esiste se la partita non è iniziata)
    if arena.current_time then
      local pl = core.get_player_by_name(pl_name)
      for _, child in ipairs(pl:get_children()) do
        if child:get_luaentity() and child:get_luaentity()._is_health_bar then
          local prev_obsv = child:get_observers()

          prev_obsv[p_name] = true
          child:set_observers(prev_obsv)
        end
      end
    end
  end

  local entity = core.add_entity(player:get_pos(), "block_league:hp_bar", core.serialize(staticdata))

  entity:set_attach(player, "", {x=0, y=19, z=0}, {x=0, y=0, z=0})
  entity:set_observers(observers)
end

local add_hp = block_league.add_hp_bar



function block_league.remove_from_hp_bars(arena, p_name, teamID)
  for _, pl_name in ipairs(arena_lib.get_players_in_team(arena, teamID)) do
    local pl = core.get_player_by_name(pl_name)
    for _, child in ipairs(pl:get_children()) do
      if child:get_luaentity() and child:get_luaentity()._is_health_bar then
        local prev_obsv = child:get_observers()

        prev_obsv[p_name] = nil
        child:set_observers(prev_obsv)
      end
    end
  end
end





core.register_entity("block_league:hp_bar", {
	initial_properties = {
		visual = "sprite",
		visual_size = {x=1, y=1/12, z=1},
		textures = {"blank.png"},
		collisionbox = {0},
		physical = false,
		static_save = false,
	},

  wielder = {},
  teamID = -1,
  _is_health_bar = true,

  on_activate = function(self, staticdata)
    local staticdata_tbl = core.deserialize(staticdata)
    local player = core.get_player_by_name(staticdata_tbl.owner)

    self.wielder = player
    self.teamID = staticdata_tbl.teamID
  end,

	on_step = function(self)
		local player = self.wielder
		local hp_bar = self.object
		local arena = arena_lib.get_arena_by_player(player:get_player_name())

		if not arena then
			hp_bar:remove()
			return
		elseif vector_distance(player:get_pos(), hp_bar:get_pos()) > 3 then -- ?
			hp_bar:remove()
			add_hp(arena, player)
			return
		end

		local hp = scale_to_default_hp(player)

		if hp == 0 then
			hp_bar:set_properties({textures = {"blank.png"}})
			self.hp = -1  -- forcing the check next step
			return
		end

		if self.hp ~= hp then
			local health_t = "bl_health_" .. hp .. ".png"

			hp_bar:set_properties({textures = {health_t}})
			self.hp = hp
		end
	end,

	on_deactivate = function(self)
		local player = self.wielder
		local arena = arena_lib.get_arena_by_player(player:get_player_name())

		if arena and not arena.in_celebration then add_hp(arena, player) end
	end
})





----------------------------------------------
---------------FUNZIONI LOCALI----------------
----------------------------------------------
---
-- credit: https://github.com/minetest/minetest/blob/6de8d77e17017cd5cc7b065d42566b6b1cd076cc/builtin/game/statbars.lua#L30-L37
function scale_to_default_hp(player)
	-- Scale "hp" to supported amount
	local current = player:get_hp(player)
	local max_display = math.max(player:get_properties().hp_max, current)
	return math.round(current / max_display * max.hp)
end