local S = core.get_translator("block_league")
local dmg = 30
local sentries = {}                     -- KEY: p_name; VALUE: sentry


local function register_sentrygun(name, def)
  if def.variant_of then
    table.insert(core.registered_items[def.variant_of]._variants, name)
  end

  weapons_lib.register_weapon(name, {
    description = S("Sentry Gun"),
    _profile_description = S("A loyal companion"),
    _variant_name = def.variant_name,
    _variant_of = def.variant_of,
    _variants = {},
    groups = {bl_weapon_sentrygun = 1},

    mesh = "bl_sentrygun.b3d",
    tiles = def.textures,
    wield_scale = {x=2.8, y=2.8, z=2.8},
    inventory_image = def.icon,
    use_texture_alpha = "clip",

    weapon_type = "ranged",
    magazine = 4,
    limited_magazine = true,
    reload_time = -1,

    crosshair = "bl_sentrygun_crosshair.png",

    can_use_weapon = function(player, action)
      return block_league.util_weapon_use_check(player, action)
    end,

    can_alter_speed = function(player)
      return block_league.util_on_can_alter_speed(player:get_player_name())
    end,

    on_recovery_end = function(player, weapon, action)
      block_league.util_on_recovery_end(player, weapon, action)
    end,

    action1 = {
      type = "custom",
      _description = S("Install. Shoots 3 times, deals @1 each. It has 20hp", "<style color=#f66c77>" .. dmg/3 .. "♥<style color=#ffffff>"),
      ammo_per_use = 1,
      range = 150,
      delay = 1.5,

      physics_override = "DEADWEIGHT",

      on_use = function(player, weapon, action)
        local p_name = player:get_player_name()
        local staticdata = core.serialize({
          owner = p_name,
          rot = player:get_look_horizontal(),
          teamID = arena_lib.get_teamID(p_name),
          textures = weapon.tiles,
          icon = weapon.inventory_image,
        })

        if sentries[p_name] and sentries[p_name]:get_luaentity() then
          sentries[p_name]:get_luaentity():_kill()
        end

        sentries[p_name] = core.add_entity(vector.add(player:get_pos(), vector.new(0,1,0)), "block_league:sentry", staticdata)
        block_league.util_update_mag_hud(p_name, weapon.name)
      end,
    }
  })
end



register_sentrygun("block_league:sentry_gun", {
  icon = "bl_sentrygun.png",
  textures = {"bl_sentrygun_texture.png"},
})

register_sentrygun("block_league:sentry_gun_silver", {
  icon = "bl_sentrygun_silver.png",
  textures = {"bl_sentrygun_texture_silver.png"},
  variant_name = S("Silver"),
  variant_of = "block_league:sentry_gun"
})

register_sentrygun("block_league:sentry_gun_gold", {
  icon = "bl_sentrygun_gold.png",
  textures = {"bl_sentrygun_texture_gold.png"},
  variant_name = S("Gold"),
  variant_of = "block_league:sentry_gun"
})

register_sentrygun("block_league:sentry_gun_diamond", {
  icon = "bl_sentrygun_diamond.png",
  textures = {"bl_sentrygun_texture_diamond.png"},
  variant_name = S("Diamond"),
  variant_of = "block_league:sentry_gun"
})