local S = core.get_translator("block_league")



----------------------------------------------
---------------LUANTI OVERRIDE----------------
----------------------------------------------
local old_death_screen = core.show_death_screen

core.show_death_screen = function(player, reason)
  local mod = arena_lib.get_mod_by_player(player:get_player_name())

  if mod == "block_league" then
    return
  else
    old_death_screen(player, reason)
  end
end
----------------------------------------------



local corpse = {
  initial_properties = {
    physical = false,
    pointable = false,
    collide_with_objects = false,
    visual = "mesh",
    mesh = "character.b3d",
    textures = {"blank.png"},
    static_save = false,
  },

  on_activate = function(self, staticdata)
    if not staticdata or staticdata == "" then self.object:remove() return end

    local staticdata_tbl = core.deserialize(staticdata)
    local obj = self.object

    obj:set_properties({textures = {staticdata_tbl.txtr .. "^[colorize:#000000:200"}})
    obj:set_rotation(staticdata_tbl.rot)
    obj:set_animation({x=162, y=166})

    core.add_particlespawner({
      amount = 40,
      time = 2,
      attached = obj,
      minvel = {x = -0.1, y =  0.9, z = -0.1},
      maxvel = {x = 0.1, y = 1.4, z = 0.1},
      minsize = 4,
      maxsize = 6.5,
      pos = {min = vector.new(-1, 0, -1), max = vector.new(1, 0, 1)},
      texture = {
          name = "bl_smg_trail2.png^[colorize:#99e550:255",
          alpha = 1.0,
          scale_tween = {
            {x = 0.2, y = 0.2},
            {x = 1, y = 1},
        }
      },
    })

    core.after(2, function()
      obj:remove()
    end)
  end
}

core.register_entity("block_league:corpse", corpse)





function block_league.death_spectate(player, arena)
  local p_to_follow
  local p_name = player:get_player_name()
  local teamID = arena.players[p_name].teamID

  for _, pl in ipairs(arena_lib.get_players_in_team(arena, teamID, true)) do
    if pl:get_hp() > 0 then
      p_to_follow = pl
      break
    end
  end

  if p_to_follow then
    player:set_eye_offset({x = 0, y = 5, z = -30}, {x=0, y=0, z=0})
    player:set_attach(p_to_follow, "", {x=0, y=-5, z=-20}, {x=0, y=0, z=0})
    arena_lib.HUD_send_msg("hotbar", p_name, S("Currently following: @1", p_to_follow:get_player_name()))

  else
    local p_pos = player:get_pos()
    local p_y = player:get_look_horizontal()
    local dummy = core.add_entity(p_pos, "weapons_lib:dummy")

    arena_lib.HUD_hide("hotbar", p_name)
    player:set_attach(dummy, "", {x=0,y=5,z=0}, {x=0, y=-math.deg(p_y), z=0})
  end
end



function block_league.reassign_dead_teammates(player, arena)
  for _, obj in ipairs(player:get_children()) do
    if obj:is_player() and arena_lib.is_player_playing(obj:get_player_name()) then
      obj:set_detach()
      block_league.death_spectate(obj, arena)
    end
  end
end