local S = core.get_translator("block_league")

local function remove_HUD() end
local function remove_spectate_HUD() end
local function stop_sounds() end



arena_lib.on_end("block_league", function(arena, winners, is_forced)
  for sp_name, _ in pairs(arena.spectators) do
    block_league.HUD_spectate_remove(arena.players, sp_name)
    remove_HUD(sp_name, true)
  end

  for pl_name, stats in pairs(arena.players) do
    local player = core.get_player_by_name(pl_name)
    local prev_physics = player:get_physics_override()

    -- zoom out twice (first during the celebration) as the first time is to create
    -- a separation from the game, whereas the latter is to prevent to keep the
    -- gunsight view after the match (I don't want to disable it as I really like
    -- the fact you can zoom during the loading phase)
    weapons_lib.reset_state(core.get_player_by_name(pl_name))

    -- 1. reset_state() mi va a riaccelerare dato che lə giocante non è più in partita.
    -- Uso questo param per ripristinare.
    -- 2. il globalstep di w_l, che capisce che deve togliere zoom, viene eseguito
    -- dopo on_end, riaccelerando lə giocante. Non posso mettere un controllo su
    -- can_alter_speed perché è a tutti gli effetti già fuori dall'arena. Da qui l'after
    core.after(0.1, function()
      if not player then return end
      player:set_physics_override(prev_physics)
    end)

    remove_HUD(pl_name)
    stop_sounds(pl_name)
    pl_name:get_skill(block_league.get_player_skill(pl_name)):disable()
    block_league.remove_player_entities(stats.entities)

    --block_league.update_storage(pl_name)
  end

  -- se è tutorial, svuota
  if arena.mode == 0 then
    for pl_name, _ in pairs(arena.players) do
      if arena.current_time == 0 then
        core.chat_send_player(pl_name, S("Looks like it was taking you too much time to finish the tutorial :("))
      end

      bl_tutorial.unload(pl_name)
    end
  end
end)



arena_lib.on_quit("block_league", function(arena, p_name, is_spectator, reason, p_properties)
  local player = core.get_player_by_name(p_name)

  if not is_spectator then
    block_league.remove_player_entities(p_properties.entities)
    block_league.remove_from_hp_bars(arena, p_name, p_properties.teamID)
    block_league.reassign_dead_teammates(player, arena)
  else
    block_league.HUD_infopanel_update_spectators(arena) -- non ha senso chiamarlo pure su on_end
  end

  -- se non si è disconnessə, sgancia la palla. A quanto pare non si sgancia da qua
  -- per chi si disconnette, prob get_player_name ritorna nullo
  if reason ~= 0 then
    if not is_spectator and arena.mode == 1 then
      local children = player:get_children()
      for _, child in pairs(children) do
        local entity = child:get_luaentity()
        -- potrebbe essere unə spettante, controllo che sia effettivamente la palla
        -- TEMP: get_luaentity() is needed for the moment, as entities on MT are
        -- half broken: they sometimes remain as an empty shell that can't be
        -- removed. If someone enters with a broken entity, we want to avoid the
        -- server going kaboom (as their get_luaentity() returns nil).
        -- See https://github.com/minetest/minetest/issues/13297
        if entity and entity._prev_player_blue then
          entity:detach() -- funzione della palla
        end
      end
    end
  end

  remove_spectate_HUD(arena, p_name, is_spectator)
  remove_HUD(p_name, is_spectator)
  stop_sounds(p_name)

  p_name:get_skill(block_league.get_player_skill(p_name)):disable()

  if arena.mode == 0 then
    bl_tutorial.unload(p_name)
  else
    block_league.HUD_infopanel_update_points_all(arena)
  end

  local p_physics = player:get_physics_override()

  -- se la gente esce mentre un'azione di un'arma è in corso (ricarica, recupero),
  -- la fisica verrebbe alterata al finire dell'azione. Per evitare ciò, salvo in
  -- p_physics la fisica impostata da arena_lib/hub (che avviene prima dell'on_quit),
  -- resetto lo stato delle armi, e per prevenire un'alterazione dovuta al reset
  -- reimposto infine la fisica
  weapons_lib.deactivate_zoom(player)
  weapons_lib.reset_state(player)
  player:set_physics_override(p_physics)
end)





----------------------------------------------
---------------FUNZIONI LOCALI----------------
----------------------------------------------

function remove_HUD(p_name, is_spectator)
  block_league.HUD_critical_remove(p_name)
  panel_lib.get_panel(p_name, "bl_stamina"):remove()
  panel_lib.get_panel(p_name, "bl_weapons"):remove()
  panel_lib.get_panel(p_name, "bl_skill"):remove()
  panel_lib.get_panel(p_name, "bl_broadcast"):remove()
  panel_lib.get_panel(p_name, "bl_scoreboard"):remove()
  panel_lib.get_panel(p_name, "bl_log"):remove()

  if is_spectator then return end

  panel_lib.get_panel(p_name, "bl_crosshair"):remove()
  panel_lib.get_panel(p_name, "bl_crosshair_overlay"):remove()
  panel_lib.get_panel(p_name, "bl_info_panel"):remove()

  if panel_lib.get_panel(p_name, "bl_keys") then
    panel_lib.get_panel(p_name, "bl_keys"):remove()
  end
end



function remove_spectate_HUD(arena, p_name, is_spectator)
  if is_spectator then
    block_league.HUD_spectate_remove(arena.players, p_name)
  else
    block_league.HUD_spectate_removeplayer(arena, p_name)
  end
end



function stop_sounds(p_name)
  audio_lib.stop_sound(p_name, "bl_voice_countdown_3")
end
