extends Node

var inventories: Dictionary = {}
var equipment: Dictionary = {}

func _ready() -> void:
  EventBus.entity_deregistered.connect(_on_dereg)

func _on_dereg(entity: Node) -> void:
  inventories.erase(entity)
  equipment.erase(entity)

func add_item(player: Node, item_id: StringName, amount: int) -> void:
  if not (multiplayer.is_server() or multiplayer.multiplayer_peer == null):
    return
  if not player in inventories:
    inventories[player] = {}
  inventories[player][item_id] = inventories[player].get(item_id, 0) + amount
  EventBus.inventory_changed.emit(player)
  if not player.is_multiplayer_authority():
    _sync_inventory.rpc_id(player.get_multiplayer_authority(), inventories[player])

func remove_item(player: Node, item_id: StringName, amount: int) -> bool:
  if not (multiplayer.is_server() or multiplayer.multiplayer_peer == null):
    return false
  if not player in inventories:
    return false
  if inventories[player].get(item_id, 0) < amount:
    return false
  inventories[player][item_id] -= amount
  if inventories[player][item_id] <= 0:
    inventories[player].erase(item_id)
  EventBus.inventory_changed.emit(player)
  if not player.is_multiplayer_authority():
    _sync_inventory.rpc_id(player.get_multiplayer_authority(), inventories[player])
  return true

func get_amount(player: Node, item_id: StringName) -> int:
  if not player in inventories:
    return 0
  return inventories[player].get(item_id, 0)

func get_inventory(player: Node) -> Dictionary:
  return inventories.get(player, {})

@rpc("authority", "reliable", "call_local")
func _sync_inventory(data: Dictionary) -> void:
  var local: Node = _find_local_player()
  if local:
    inventories[local] = data
    EventBus.inventory_changed.emit(local)

func _find_local_player() -> Node:
  for p in get_tree().get_nodes_in_group("player"):
    if p.is_multiplayer_authority():
      return p
  return null
