local recursive_time = 0.1
local SPEED_LOW = block_league.SPEED * block_league.SHOOT_SPEED_MULTIPLIER



function block_league.stamina_refill_loop(arena)
  if not arena.in_game then return end

  for pl_name, _ in pairs(arena.players) do
    local player = minetest.get_player_by_name(pl_name)
    local health = player:get_hp()
    local stamina = arena.players[pl_name].stamina
    local max_stamina = arena.players[pl_name].stamina_max

    -- se è vivo, senza palla e con energia non al massimo
    if health > 0 and player:get_meta():get_int("bl_has_ball") == 0 and stamina < max_stamina then
      arena.players[pl_name].stamina = stamina + 1
      block_league.HUD_stamina_update(arena, pl_name)
    end
  end

  minetest.after(recursive_time, function() block_league.stamina_refill_loop(arena) end)
end



function block_league.stamina_drain(arena, w_name)
  if not arena.in_game or not arena.players[w_name] then return end -- al posto di controllare se è in partita e se non è spettatore; meno chiamate

  local wielder = minetest.get_player_by_name(w_name)
  local w_meta = wielder:get_meta()

  if w_meta:get_int("bl_has_ball") == 0 then return end

  local w_data = arena.players[w_name]

  if w_data.stamina > 0 then
    w_data.stamina = w_data.stamina -2
    block_league.HUD_stamina_update(arena, w_name)
  else
    w_data.stamina = 0 -- in case went to -1
    if w_meta:get_int("wl_slowed_down") == 0 and
       w_meta:get_int("wl_is_speed_locked") == 0 then
      wielder:set_physics_override({speed = SPEED_LOW})
      w_meta:set_int("wl_slowed_down", 1)
    end
    return
  end

  minetest.after(recursive_time, function() block_league.stamina_drain(arena, w_name) end)
end
