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

/**
 * @param {number} min The minimum integer
 * @param {number} max The maximum integer
 * @returns {number} A random integer between the `min` and `max` parameters (inclusive)
 */
const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

const maxGrowth = 3;

/** @type {import("@minecraft/server").BlockCustomComponent} */
const CustomCropGrowthBlockComponent = {
    onRandomTick({ block, dimension }) {
        const growthChance = 1 / 3;
        if (Math.random() > growthChance) return;

        const growth = block.permutation.getState("ecbl_bc:growth");
        block.setPermutation(block.permutation.withState("ecbl_bc:growth", growth + 1));
    },
    onPlayerInteract({ block, dimension, player }) {
        if (!player) return;

        const equippable = player.getComponent("minecraft:equippable");
        if (!equippable) return;

        const mainhand = equippable.getEquipmentSlot(EquipmentSlot.Mainhand);
        if (!mainhand.hasItem() || mainhand.typeId !== "minecraft:bone_meal") return;

        if (player.getGameMode() === GameMode.creative) {
            // Grow crop fully
            block.setPermutation(block.permutation.withState("ecbl_bc:growth", 3));
            dimension.runCommand(`particle minecraft:crop_growth_emitter ${block.location.x} ${block.location.y + 1} ${block.location.z}`)
            dimension.runCommand(`playsound item.bone_meal.use @a ${block.location.x} ${block.location.y + 1} ${block.location.z}`)

        } else {
            let growth = block.permutation.getState("ecbl_bc:growth");

            // Add random amount of growth
            growth += randomInt(1, maxGrowth - growth);
            block.setPermutation(block.permutation.withState("ecbl_bc:growth", growth));

            // Decrement stack
            if (mainhand.amount > 1) mainhand.amount--;
            else mainhand.setItem(undefined);
        }
    },
};

world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
    blockComponentRegistry.registerCustomComponent(
        "ecbl_bc:custom_crop_growth",
        CustomCropGrowthBlockComponent
    );
});


/////


// Função auxiliar para simular atraso
function delay(ms) {
    return new Promise(resolve => system.runTimeout(resolve, ms));
}

// Evento de colocação de bloco por um jogador
world.afterEvents.playerPlaceBlock.subscribe((event) => {
    const { block, dimension } = event;

    // Verifica se o bloco colocado é "ecbl_bc:corn_block"
    if (block.typeId === "ecbl_bc:corn_block") {
        // Verifica se o bloco acima está vazio
        if (block.above()?.typeId === "minecraft:air") {
            if (block.above()?.typeId !== "ecbl_bc:corn_block") {

                dimension.runCommandAsync(`setblock ${block.location.x} ${block.location.y + 1} ${block.location.z} ecbl_bc:corn_block["ecbl_bc:growth_corn"=0,"ecbl_bc:growth_up_or_down"=true]`);

                // Adiciona um atraso de 3 segundos (3000 milissegundos)
                delay(2400).then(() => {

                    // Comando para verificar se um jogador tem o item
                    const testForCommand = `testforblock ${block.location.x} ${block.location.y} ${block.location.z} ecbl_bc:corn_block["ecbl_bc:growth_corn"=0,"ecbl_bc:growth_up_or_down"=false]`;
                    const testForCommand2 = `testforblock ${block.location.x} ${block.location.y + 1} ${block.location.z} ecbl_bc:corn_block["ecbl_bc:growth_corn"=0,"ecbl_bc:growth_up_or_down"=true]`;

                    world.getAllPlayers().forEach(player => {
                        player.runCommandAsync(testForCommand).then((result) => {
                            if (result.successCount > 0) {

                                world.getAllPlayers().forEach(player => {
                                    player.runCommandAsync(testForCommand2).then((result) => {
                                        if (result.successCount > 0) {

                                            dimension.runCommandAsync(`setblock ${block.location.x} ${block.location.y} ${block.location.z} ecbl_bc:corn_block["ecbl_bc:growth_corn"=1,"ecbl_bc:growth_up_or_down"=false]`);
                                            dimension.runCommandAsync(`setblock ${block.location.x} ${block.location.y + 1} ${block.location.z} ecbl_bc:corn_block["ecbl_bc:growth_corn"=1,"ecbl_bc:growth_up_or_down"=true]`);

                                            delay(2400).then(() => {

                                                // Comando para verificar se um jogador tem o item
                                                const testForCommand = `testforblock ${block.location.x} ${block.location.y} ${block.location.z} ecbl_bc:corn_block["ecbl_bc:growth_corn"=1,"ecbl_bc:growth_up_or_down"=false]`;
                                                const testForCommand2 = `testforblock ${block.location.x} ${block.location.y + 1} ${block.location.z} ecbl_bc:corn_block["ecbl_bc:growth_corn"=1,"ecbl_bc:growth_up_or_down"=true]`;

                                                world.getAllPlayers().forEach(player => {
                                                    player.runCommandAsync(testForCommand).then((result) => {
                                                        if (result.successCount > 0) {

                                                            world.getAllPlayers().forEach(player => {
                                                                player.runCommandAsync(testForCommand2).then((result) => {
                                                                    if (result.successCount > 0) {

                                                                        dimension.runCommandAsync(`setblock ${block.location.x} ${block.location.y} ${block.location.z} ecbl_bc:corn_block["ecbl_bc:growth_corn"=2,"ecbl_bc:growth_up_or_down"=false]`);
                                                                        dimension.runCommandAsync(`setblock ${block.location.x} ${block.location.y + 1} ${block.location.z} ecbl_bc:corn_block["ecbl_bc:growth_corn"=2,"ecbl_bc:growth_up_or_down"=true]`);

                                                                    }
                                                                });
                                                            })
                                                        }
                                                    })
                                                })
                                            })
                                        }
                                    });
                                })
                            }
                        })
                    })
                })
            }
        }
    }
});

world.afterEvents.playerBreakBlock.subscribe(event => {
    const { dimension, block } = event;
    const blockPosition = block.location;
    if (event.brokenBlockPermutation.type.id == "ecbl_bc:corn_block") {
        dimension.runCommand(`fill ${block.location.x} ${block.location.y - 1} ${block.location.z} ${block.location.x} ${block.location.y - 1} ${block.location.z} air replace ecbl_bc:corn_block`)
    }
})