import { Block, Dimension, ItemComponentTypes, ItemStack, system } from "@minecraft/server";
import { checkTopOrBottomNeighborHasTag } from "../../../library/blockManager";
/**
 * Evento onRandomTick del componente resourceRecyclerComponent
 * Addon: Electrical Creativity BP
 * @param {{block: Block, dimension: Dimension}} event
 */
export const resourceRecyclerOnTickEvent = ({block, dimension}) => {
    try {
        if (!block.permutation.getState("nps_ec:power")) return;
        if (!block.permutation.getState("nps_ec:active")) return;
        if (checkTopOrBottomNeighborHasTag(block, 'power:on')) {
            const blockAbove = block.above(1);
            if (!blockAbove || blockAbove.typeId !== "minecraft:chest") return;

            const container = blockAbove.getComponent("inventory")?.container;
            if (!container) return;

            for (let i = 0; i < container.size; i++) {
                const item = container.getItem(i);
                if (!item) continue;

                const durability = item.getComponent(ItemComponentTypes.Durability);
                if (!durability) continue; // no es herramienta

                const remaining = durability.maxDurability - durability.damage;
                const percent = (remaining / durability.maxDurability) * 100;

                if (percent <= 10) {
                    // reemplazar ítem dañado por Plasma Scrap
                    container.setItem(i, new ItemStack("nps_ec:plasma_scrap", 1));
                    const permutation = block.permutation.withState("nps_ec:processing", true);
                    block.setPermutation(permutation);
                    system.runTimeout(() => {
                        try {
                            const permutation = block.permutation.withState("nps_ec:processing", false);
                            block.setPermutation(permutation);
                        } catch { }
                    }, 2)
                    dimension.runCommand(`particle nps_ec:resource_recycler ${block.x} ${block.y+0.5} ${block.z}`);
                    return;
                }
            }

            // Si no se está procesando
            const permutation = block.permutation.withState("nps_ec:processing", false);
            block.setPermutation(permutation);
        }
    } catch { }
}