import * as mc from "@minecraft/server";
import * as utils from "../../utils/index";
import { ComponentNPC } from "./base";
export class VirtualInventoryComponent extends ComponentNPC {
    get Inventory() {
        var _a;
        if (!this.npc)
            return {};
        return (_a = utils.readDynamicProperty(this.npc.Entity, "inventory")) !== null && _a !== void 0 ? _a : {};
    }
    set Inventory(v) {
        if (this.npc)
            utils.writeDynamicProperty(this.npc.Entity, "inventory", v);
    }
    get Count() {
        if (!Object.values(this.Inventory).length)
            return 0;
        return Object.values(this.Inventory).reduce((a, b) => a + b);
    }
    addItems(items) {
        var _a;
        const currentInventory = this.Inventory;
        Object.keys(items).forEach(item => {
            if (!currentInventory[item])
                currentInventory[item] = 0;
            currentInventory[item] += items[item];
        });
        this.Inventory = currentInventory;
        (_a = this.npc) === null || _a === void 0 ? void 0 : _a.broadcastEvent("get_item");
    }
    transferItems(target, itemNames) {
        var _a;
        const targetInventory = utils.getInventoryContainer(target);
        if (!targetInventory)
            return;
        const cachedInventory = this.Inventory;
        itemNames = itemNames !== null && itemNames !== void 0 ? itemNames : Object.keys(cachedInventory);
        itemNames.filter(itemName => Boolean(cachedInventory[itemName])).forEach(itemName => {
            while (cachedInventory[itemName] > 0) {
                const item = new mc.ItemStack(itemName);
                item.amount = utils.clamp(cachedInventory[itemName], 1, item.maxAmount);
                cachedInventory[itemName] -= item.amount;
                if (targetInventory.emptySlotsCount > 0) {
                    targetInventory.addItem(item);
                }
                else {
                    target.dimension.spawnItem(item, target.location);
                }
            }
        });
        this.Inventory = cachedInventory;
        (_a = this.npc) === null || _a === void 0 ? void 0 : _a.broadcastEvent("give_item");
    }
}
