import * as mc from "@minecraft/server";
import * as utils from "../../utils/index";
export class VirtualInventoryComponent extends utils.ActorComponent {
    constructor() {
        super(...arguments);
        this.inventory = new Map();
    }
    get Count() {
        let totalCount = 0;
        this.inventory.forEach(amount => {
            totalCount += amount;
        });
        return totalCount;
    }
    onComponentAdded() {
        var _a;
        this.inventory = new Map(Object.entries((_a = utils.readDynamicProperty(this.actor, utils.addName("virtual_inventory"))) !== null && _a !== void 0 ? _a : {}));
    }
    addItem(item) {
        const currentAmount = this.inventory.get(item.typeId);
        if (currentAmount)
            item.amount += currentAmount;
        this.inventory.set(item.typeId, item.amount);
        this.updateProp();
    }
    getItem(id, remove) {
        const item = this.inventory.get(id);
        if (remove)
            this.inventory.delete(id);
        this.updateProp();
        if (item)
            return new mc.ItemStack(id, item);
    }
    getAllItems(remove) {
        const items = [];
        this.inventory.forEach((amount, id) => {
            while (amount > 0) {
                const item = new mc.ItemStack(id);
                item.amount = Math.min(amount, item.maxAmount);
                items.push(item);
                amount -= item.amount;
            }
        });
        if (remove)
            this.inventory.clear();
        this.updateProp();
        return items;
    }
    updateProp() {
        utils.writeDynamicProperty(this.actor, utils.addName("virtual_inventory"), Object.fromEntries(this.inventory));
    }
}
