-- Copyright © 2014-2020 4aiman, Hugo Locurcio and contributors
-- Copyright © 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

local max = {hp = 20}



function block_league.add_hp_bar(arena, object, height)
  if arena.mode == 0 then return end -- niente barre nel tutorial, anche perché non esiste teamID

  local guid = object:get_guid()
  local is_player = object:is_player()
  local teamID = is_player and arena.players[guid].teamID or object:get_luaentity()._teamID
  local staticdata = {guid = guid, 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

    -- se è unə giocante e la partita è iniziata (current_time non esiste sennò),
    -- renderizzaje le barre di chi era già dentro - sia giocanti che entità
    if is_player then
      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[guid] = true
            child:set_observers(prev_obsv)
          end
        end

        for _, ent in pairs(arena.players[pl_name].entities) do
          if ent:get_luaentity() then -- perché figurati se Luanti non dà problemi con le entità che potrebbero tornare nulle
            for _, child in ipairs(ent:get_children()) do
              if child:get_luaentity() and child:get_luaentity()._is_health_bar then
                local prev_obsv = child:get_observers()

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

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

  entity:set_attach(object, "", {x=0, y= height or 19, z=0}, {x=0, y=0, z=0}) -- y = 19 è quella base per giocanti
  entity:set_observers(observers)
end

local add_hp = block_league.add_hp_bar



function block_league.remove_from_hp_bars(arena, p_name, teamID)
  -- nascondi a p_name barre di giocanti/entità della sua squadra (potrebbe rientrare
  -- nella squadra avversaria e vederle entrambe)
  for _, pl_name in ipairs(arena_lib.get_players_in_team(arena, teamID)) do -- giocanti
    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

    for _, ent in pairs(arena.players[pl_name].entities) do -- entità
      if ent:get_luaentity() then -- perché figurati se Luanti non dà problemi con le entità che potrebbero tornare nulle
        for _, child in ipairs(ent: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
  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,
	},

  _holder = {},
  _teamID = -1,
  _is_player = false,
  _is_health_bar = true,

  on_activate = function(self, staticdata)
    local staticdata_tbl = core.deserialize(staticdata)
    local guid = staticdata_tbl.guid
    local holder = core.objects_by_guid[guid]

    self._holder = holder
    self._teamID = staticdata_tbl.teamID
    self._is_player = guid:sub(1,1) == "@" and false or true
  end,

	on_step = function(self)
		local obj = self._holder
		local hp_bar = self.object

    if not obj then return end

		local hp = scale_to_default_hp(obj)

		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,

  -- la barra viene rimossa automaticamente quando sganciata dall'entità genitrice
  on_detach = function(self, parent)
    self.object:remove()
  end,

	on_deactivate = function(self)
		local holder = self._holder
		local arena = arena_lib.get_arena_by_player(holder:get_player_name())

		if arena and not arena.in_celebration then add_hp(arena, holder) 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
