class_name Inventory extends Resource

signal item_added(item: Item, quantity: int)
signal item_removed(item: Item, remaining: int)
signal updated

@export var initial_items: Array[ItemInstance]
@export var max_capacity: int = 6

var items: Dictionary[int, ItemInstance]
var empty_slots: int:
    get: return max_capacity - size()

func _init():
    call_deferred("_ready")

func _ready():
    for item in initial_items:
        items[_get_id(item.item)] = item
    updated.emit()

func size() -> int:
    return items.size()

func _get_id(item: Item) -> int:
    return item.get_instance_id()

func _item_eq(a: Item, b: ItemInstance) -> bool:
    return a.item == b

func has_item(item: Item) -> bool:
    return items.has(_get_id(item))

func find(item: Item) -> Option:
    match items.get(_get_id(item)):
        null: return Option.none
        var found: return Option.some(found)

func add_item(item: Item, quantity: int = 1):
    var id = _get_id(item)
    var updated_quantity = quantity
    if items.has(id):
        items[id].quantity += quantity
        updated_quantity = items[id].quantity
    else:
        items[id] = ItemInstance.new(item, quantity)

    item_added.emit(item, updated_quantity)
    updated.emit()

func remove_item(item: Item, quantity: int = 1):
    if find(item):
        item.quantity -= quantity
        if item.quantity <= 0:
            items.erase(_get_id(item))
        item_removed.emit(item, item.quantity)
        updated.emit()

func iter() -> Iterator:
    return DictionaryIterator.new(items)
