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

system.beforeEvents.startup.subscribe((initEvent) => {
    initEvent.blockComponentRegistry.registerCustomComponent("rustic:sugar_cane", {
        onRandomTick: e => {
            const { block, dimension } = e;
            if (block.below().typeId != "rustic:fertile_soil")return;
            if (block.above().isAir) block.above().setType("rustic:sugar_cane");
            else if (block.above().typeId == "rustic:sugar_cane" && block.above(2).isAir) block.above(2).setType("rustic:sugar_cane");
        },
    });
});

world.beforeEvents.playerInteractWithBlock.subscribe(eventData => {
    const block = eventData.block;
    const player = eventData.player;
    const item = eventData.itemStack;

    if (block.typeId != "rustic:sugar_cane")return;
    if (item == undefined) return;
    if (item.typeId != 'minecraft:bone_meal') return;

    const equipment = player.getComponent('equippable');

    system.run( () => {
        if (block.above().isAir && block.below().hasTag("fertile_soil")) block.above().setType("rustic:sugar_cane"), block.above(2).setType("rustic:sugar_cane");
        else if (block.above().isAir && block.below().hasTag("cane") && !block.below(2).hasTag("cane"))block.above().setType("rustic:sugar_cane");
        //else if (block.above().typeId == "rustic:sugar_cane" && block.above(2).isAir && !block.below().hasTag("cane")) block.above(2).setType("rustic:sugar_cane");
        else return;

        block.dimension.spawnParticle("minecraft:crop_growth_emitter", block.center());
        block.dimension.playSound("item.bone_meal.use", block.center());
        if (player.getGameMode() !== "creative") {
            if (item.amount > 1) {
                item.amount -= 1;
                equipment.setEquipment('Mainhand', item);
            } else if (item.amount === 1) {
                equipment.setEquipment('Mainhand', undefined);
            }
        }
    })

    eventData.cancel = true
});