extends Node

const LOOT_SCENE: PackedScene = preload("res://scenes/entities/loot/loot_drop.tscn")

func _loot_root() -> Node3D:
  var n: Node = get_node_or_null("/root/World/EntityRoot/Loot")
  if n == null:
    n = get_node_or_null("/root/Dungeon/EntityRoot/Loot")
  return n

func drop_loot_for(entity: Node, pos: Vector3) -> void:
  if not (multiplayer.is_server() or multiplayer.multiplayer_peer == null):
    return
  var root := _loot_root()
  if root == null:
    return
  var amount: int = 1
  var item_id: StringName = &"essence"
  if entity.is_in_group("boss"):
    amount = 5 + randi() % 5
  var loot: Area3D = LOOT_SCENE.instantiate()
  loot.item_id = item_id
  loot.amount = amount
  loot.name = "Loot_%d" % (Time.get_ticks_msec() + randi() % 1000)
  root.add_child(loot, true)
  loot.global_position = pos + Vector3(randf_range(-0.5, 0.5), 0.4, randf_range(-0.5, 0.5))
  EventBus.loot_dropped.emit([item_id], loot.global_position)
