import { system, world, BlockPermutation, Player, EquipmentSlot, GameMode } from "@minecraft/server";

const saw = {
    onMineBlock(event) {
        const { block, source, minedBlockPermutation } = event;

        // Ensure the source is a player.
        if (!(source instanceof Player)) return;
        // Check if the block is a log
        if (minedBlockPermutation.type.id.endsWith("_log")) {
            
            
            const dimension = block.dimension;
            const startY = block.location.y;
            const startX = block.location.x;
            const startZ = block.location.z;

            const visited = new Set();
            const connectedLogs = [];
            const queue = [block];

            // Limits and settings
            const MAX_RADIUS = 3; // Maximum radius in X and Z directions
            const BREAK_DELAY = 1; // Delay between breaking each block in ticks

            // Function to process the queue in batches
            const processQueue = () => {
                const BATCH_SIZE = 20; // Number of blocks to process per tick
                let count = 0;

                while (queue.length > 0 && count < BATCH_SIZE) {
                    const currentBlock = queue.shift();
                    const blockPos = `${currentBlock.location.x},${currentBlock.location.y},${currentBlock.location.z}`;

                    if (visited.has(blockPos)) continue;
                    visited.add(blockPos);

                    // Check if the block is within radius limits
                    const withinRadius =
                        Math.abs(currentBlock.location.x - startX) <= MAX_RADIUS &&
                        Math.abs(currentBlock.location.z - startZ) <= MAX_RADIUS &&
                        currentBlock.location.y <= startY + 25;

                    if (!withinRadius) continue;

                    connectedLogs.push(currentBlock);
                    count++;

                    const directions = [
                        { x: 1, y: 0, z: 0 },
                        { x: -1, y: 0, z: 0 },
                        { x: 0, y: 0, z: 1 },
                        { x: 0, y: 0, z: -1 },
                        { x: 0, y: 1, z: 0 },
                        { x: 0, y: -1, z: 0 },
                    ];

                    for (const dir of directions) {
                        const adjacentBlock = dimension.getBlock({
                            x: currentBlock.location.x + dir.x,
                            y: currentBlock.location.y + dir.y,
                            z: currentBlock.location.z + dir.z,
                        });

                        if (
                            adjacentBlock &&
                            (adjacentBlock.type.id.endsWith("_leaves") || adjacentBlock.type.id.endsWith("_log"))

                        ) {
                            queue.push(adjacentBlock);
                        }
                    }
                }

                if (queue.length > 0) {
                    system.runTimeout(processQueue, 1); // Schedule the next batch
                } else {
                    // Once all logs are identified, break them sequentially
                    breakLogsSequentially(source, connectedLogs);
                }
            };

            processQueue(); // Start processing the tree
        }
    },
};

// Function to break logs sequentially
function breakLogsSequentially(player, logs) {
    if (logs.length === 0) return;

    const BREAK_DELAY = 1; // Delay between breaking each block in ticks

    const breakNextLog = () => {
        const block = logs.shift();
        if (block) {
            block.dimension.runCommandAsync(`setblock ${block.location.x} ${block.location.y} ${block.location.z} air destroy`);
            system.runTimeout(breakNextLog, BREAK_DELAY);
        }
    };

    breakNextLog();
}

export default saw;
