class_name Inventory extends Resource

var initial_items: Array[ItemInstance]
var items: Dictionary[RID, ItemInstance]
@export var max_capacity: int = 6

var size: int:
    get: return items.size()

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

func _init():
    call_deferred("_ready")

func _ready():
    print(initial_items.size())
    for item in initial_items:
        items[item.get_rid()] = item
        print('setting', item)

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

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

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

func add_item(item: Item, quantity: int = 1):
    var rid = item.get_rid()
    var inst = items.get_or_add(rid)
    inst.quantity += quantity
    item_added.emit(item, inst.quantity)
    updated.emit()

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

func _iter_continue(iter: Array) -> bool:
    return iter[0].size()

func _iter_init(iter: Array) -> bool:
    iter[0] = items.keys()
    return _iter_continue(iter)

func _iter_next(iter: Array) -> bool:
    iter[0] += 1
    return _iter_continue(iter)

func _iter_get(iter: Variant) -> ItemInstance:
    var rid = iter[0]
    iter.remove_at(0)
    return items.get(rid)
