import { Block, system } from "@minecraft/server";

/**
 * Evento onEvent del componente digitalBlockComponent
 * Addon: Electrical Creativity BP
 * @param {Block} block 
 */
export const digitalBlockOnEvent = (block) => {
    try {
        if (block.permutation.getState("nps_ec:active") == 0 && block.permutation.getState("nps_ec:power") == 0) {
            block.setPermutation(block.permutation.withState("nps_ec:active", 1));
            block.dimension.runCommand(`particle nps_ec:digital_block ${block.location.x} ${block.location.y + 0.5} ${block.location.z}`);
            let count = 0;

            const duration = Math.floor(Math.random() * 10) + 100;
            const job = system.runInterval(() => {
                try {
                    count++;
                    block.dimension.runCommand(`particle nps_ec:digital_block ${block.location.x} ${block.location.y + 0.5} ${block.location.z}`);
                    if (count > 3) {
                        system.clearRun(job);
                    }

                    if (!block.permutation.getState("nps_ec:active")) {
                        system.clearRun(job);
                    }
                } catch {
                    system.clearRun(job)
                }
            }, duration/4);
            system.runTimeout(() => {
                try {
                    block.setPermutation(block.permutation.withState("nps_ec:active", 0));
                } catch { }
            }, duration);
        }
    } catch { }
}