import { world, InputButton, ButtonState } from '@minecraft/server';
import { GrowthRecipes } from '../../recipes/recipes.js';
import { PLAYER_SNEAK_GROW_ITEM, WORLD_SNEAK_GROW_CHANCE } from '../../settings/settings.js';
import { getEntityHeldItem } from '../../utils/players.js';
import { FSItemTags, FSTags } from '../../constants.js';
import { BlockUtils as W } from '../../ftb_bedrock_bedrock_utils_dist_bedrock_utils.js';

world.afterEvents.playerButtonInput.subscribe((eventData) => {
    if (eventData.button !== InputButton.Sneak || eventData.newButtonState !== ButtonState.Pressed) {
        return;
    }
    const player = eventData.player;
    if (PLAYER_SNEAK_GROW_ITEM.getValue(player)) {
        if (!isHoldingItem(player)) {
            return;
        }
    }
    const range = 5;
    const number = WORLD_SNEAK_GROW_CHANCE.getValue() / 100.0;
    if (number === 0) {
        return;
    }
    const blockLocationIterator = W.getBlocksInRange(player.dimension.getBlock(player.location), range);
    for (const blockLocation of blockLocationIterator) {
        const block = player.dimension.getBlock(blockLocation);
        if (!block) {
            return;
        }
        for (let processor of GrowthRecipes.PROCESSORS) {
            if (Math.random() >= number) {
                continue;
            }
            if (!processor.canProcess(block)) {
                continue;
            }
            if (processor.progressStage(block)) {
                processor.onStageProgressed?.(block);
                break;
            }
            else {
                processor.onStageProgressedFailed?.(block);
            }
        }
    }
});
function isHoldingItem(player) {
    const itemStack = getEntityHeldItem(player);
    if (!itemStack) {
        return false;
    }
    return itemStack.hasTag(FSItemTags.CAN_GROW_CROPS) || FSTags.MINECRAFT_HOES.includes(itemStack?.typeId);
}
