import * as mc from "@minecraft/server";
import { NAMESPACE } from "../anvilConstants";
import { restoreInventory } from "../inventoryManager/restoreInventory";
import { saveInventory } from "../inventoryManager/saveInventory";
export function saveBackpackContainer(data) {
    if (data.id === `${NAMESPACE}:backpack_pickup`) {
        const entity = data.sourceEntity;
        const id = entity?.getDynamicProperty(`${NAMESPACE}:backpack_container_id`);
        const itemsSaved = saveInventory(entity, id);
        const item = new mc.ItemStack(`${NAMESPACE}:backpack`, 1);
        item.setDynamicProperty(`${NAMESPACE}:backpack_container_id`, id);
        item.setLore([`Items: ${itemsSaved}`]);
        entity.dimension.spawnItem(item, entity.location);
        entity.remove();
    }
}
export function backpackPlaceEvent(data) {
    const itemStack = data.itemStack;
    if (itemStack && itemStack.typeId === `${NAMESPACE}:backpack`) {
        const block = data.block;
        const id = itemStack.getDynamicProperty(`${NAMESPACE}:backpack_container_id`);
        const blockFace = data.blockFace;
        let location = { x: block.location.x + 0.5, y: block.location.y + 0.5, z: block.location.z + 0.5 };
        switch (blockFace) {
            case 'Up':
                location.y += 0.5;
                break;
            case 'Down':
                location.y -= 1.5;
                break;
            case 'North':
                location.z -= 1;
                break;
            case 'South':
                location.z += 1;
                break;
            case 'West':
                location.x -= 1;
                break;
            case 'East':
                location.x += 1;
                break;
        }
        const backpack = block.dimension.getEntities({
            location: location,
            type: `${NAMESPACE}:backpack_entity`,
            closest: 1,
            maxDistance: 0.5
        })[0];
        if (backpack) {
            backpack.setDynamicProperty(`${NAMESPACE}:backpack_container_id`, id ?? backpack.id);
            if (id) {
                restoreInventory(backpack, id);
            }
        }
    }
}
