import { damageEntityHeldItem, getBlocksInRange, calculateItemDamageAmount } from '../../utils/utils.js';
import { SickleRecipes, GrowthRecipes } from '../../recipes/recipes.js';
import { MinecraftBlockTypes } from '../../minecraft_vanilla_data.js';

const DENIED_BLOCKS = [MinecraftBlockTypes.SweetBerryBush, MinecraftBlockTypes.MelonStem, MinecraftBlockTypes.PumpkinStem];
const SICKLE_RANGE = 5;
// They amount we damage is half of what it would've been if we broke them one by one
function calculateItemDamage(itemStack, amount) {
    const number = calculateItemDamageAmount(itemStack, amount);
    return Math.ceil(number / 2.0);
}
class SickleItemComponent {
    constructor() {
        this.onMineBlock = (event) => {
            const block = event.minedBlockPermutation;
            const player = event.source;
            for (const breakProcessor of SickleRecipes.PROCESSORS) {
                if (breakProcessor.canProcess(block.type.id)) {
                    const number = breakProcessor.process(event.block, player, SICKLE_RANGE);
                    if (number === 0) {
                        return;
                    }
                    damageEntityHeldItem(player, calculateItemDamage(event.itemStack, number), event.itemStack);
                }
            }
        };
        this.onUseOn = (event) => {
            const block = event.block;
            const dimension = block.dimension;
            const entity = event.source;
            const blocksInRange = getBlocksInRange(block, SICKLE_RANGE, false);
            let blockChanged = 0;
            for (const blocksInRangeElement of blocksInRange) {
                const blockInRange = dimension.getBlock(blocksInRangeElement);
                if (DENIED_BLOCKS.includes(blockInRange.typeId)) {
                    continue;
                }
                for (const processor of GrowthRecipes.PROCESSORS) {
                    if (processor.canBeHarvested(blockInRange)) {
                        if (processor.harvest(blockInRange, entity)) {
                            blockChanged++;
                            break;
                        }
                    }
                }
            }
            if (blockChanged <= 0) {
                return;
            }
            damageEntityHeldItem(entity, calculateItemDamage(event.itemStack, blockChanged), event.itemStack);
        };
    }
}

export { SickleItemComponent };
