import { EquipmentSlot, GameMode, world } from "@minecraft/server";
import { SuppStates } from "../reg/suppStates";
import { randomInt } from "../util/mthUtils";
const MAX_GROWTH = 7;
/** @type {import("@minecraft/server").BlockCustomComponent} */
const CustomCropGrowthBlockComponent = {
    onRandomTick(event) {
        const block = event.block;
        const growthChance = 1 / 3;
        if (Math.random() > growthChance)
            return;
        let growth = block.permutation.getState(SuppStates.Growth);
        // If already at max growth, do nothing
        if (growth >= MAX_GROWTH)
            return;
        // Increase growth stage
        block.setPermutation(block.permutation.withState(SuppStates.Growth, Math.min(growth + 1, MAX_GROWTH)));
    },
    onPlayerInteract(event) {
        const block = event.block;
        const player = event.player;
        const dimension = block.dimension;
        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;
        let growth = block.permutation.getState(SuppStates.Growth);
        // If already at max growth, do nothing
        if (growth >= MAX_GROWTH)
            return;
        if (player.getGameMode() === GameMode.creative) {
            // Grow crop fully
            block.setPermutation(block.permutation.withState(SuppStates.Growth, MAX_GROWTH));
        }
        else {
            // Add random amount of growth, ensuring it does not exceed MAX_GROWTH
            growth += randomInt(1, MAX_GROWTH - growth);
            block.setPermutation(block.permutation.withState(SuppStates.Growth, Math.min(growth, MAX_GROWTH)));
            // Decrement stack
            if (mainhand.amount > 1)
                mainhand.amount--;
            else
                mainhand.setItem(undefined);
        }
        // Play effects
        const effectLocation = block.center();
        dimension.playSound("item.bone_meal.use", effectLocation);
        dimension.spawnParticle("minecraft:crop_growth_emitter", effectLocation);
    }
};
world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
    blockComponentRegistry.registerCustomComponent("razz_sup:flax_growth", CustomCropGrowthBlockComponent);
});
