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 = core.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
    local sk_name = block_league.get_equipped_skill(pl_name)
    local skill = skills.get_def(sk_name)

    -- se è vivə, 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
       and (skill._type == "passive" or not skills.get_active_skills(pl_name, "block_league")[sk_name]) then
      arena.players[pl_name].stamina = stamina + 1
      block_league.HUD_stamina_update(arena, pl_name)
    end
  end

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



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

  local wielder = core.get_player_by_name(p_name)
  local w_meta = wielder:get_meta()

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

  local w_data = arena.players[p_name]

  if w_data.stamina > 0 then
    w_data.stamina = w_data.stamina -2
    block_league.HUD_stamina_update(arena, p_name)
  else
    w_data.stamina = 0 -- in case went to -1
    block_league.HUD_stamina_update(arena, p_name) -- same as above
    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

  core.after(recursive_time, function() block_league.stamina_drain(arena, p_name) end)
end



function block_league.add_stamina(arena, p_name, amount)
  if not arena or not arena.players[p_name] then return end

  arena.players[p_name].stamina = arena.players[p_name].stamina + amount
  block_league.HUD_stamina_update(arena, p_name)
end



function block_league.subtract_stamina(arena, p_name, amount)
  if not arena or not arena.players[p_name] then return end

  arena.players[p_name].stamina = arena.players[p_name].stamina - amount
  block_league.HUD_stamina_update(arena, p_name)
end



function block_league.has_enough_stamina(arena, p_name, amount)
  if not arena or not arena.players[p_name] then return end

  return arena.players[p_name].stamina >= amount
end