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

function getOffsets(radius = 5, xRadius = radius, yRadius = radius, zRadius = radius) {
    const offsets = [];
    for (let dx = -xRadius; dx <= xRadius; dx++) {
        for (let dy = -yRadius; dy <= yRadius; dy++) {
            for (let dz = -zRadius; dz <= zRadius; dz++) {
                let dst = Math.sqrt(dx * dx + dy * dy + dz * dz);
                if (4 <= dst && dst <= radius) {
                    offsets.push({dx, dy, dz})
                }
            }
        }
    }
    return offsets;
}

const OFFSETS = getOffsets(5, 5, 10, 5);


export function breakLeaves(player) {
    const playerLocation = player.location;
    for (const offset of OFFSETS) {
        if (Math.random() >= 0.9) {
            continue;
        }
        const x = playerLocation.x + offset.dx;
        const y = playerLocation.y + offset.dy;
        const z = playerLocation.z + offset.dz;
        const block = player.dimension.getBlock({x: x, y: y, z: z});
        const permutationMatches = block.permutation.type.id.includes("leaves") || block.permutation.type.id.includes("log");
        if (permutationMatches) {
            system.run(() => {
                player.dimension.runCommand(`setblock ${x} ${y} ${z} minecraft:air destroy`);

                player.dimension.runCommand(`execute positioned ${x} ${y} ${z} run fill ~-1~-1~-1 ~1~1~1 air replace leaves`);
                player.dimension.runCommand(`execute positioned ${x} ${y} ${z} run fill ~-1~-1~-1 ~1~1~1 air replace leaves2`);
                player.dimension.runCommand(`execute positioned ${x} ${y} ${z} run fill ~-1~-1~-1 ~1~1~1 air replace log`);
                player.dimension.runCommand(`execute positioned ${x} ${y} ${z} run fill ~-1~-1~-1 ~1~1~1 air replace log2`);
            });
        }
    }
}