import { world, system, ItemStack } from '@minecraft/server';
import { FSItemTags, MCBlockStates, FSBlocks, MCSounds } from '../../constants.js';
import { getBlockState, spawnItemAtBlock, damageEntityHeldItem, calculateItemDamageAmount, updateBlockState, playSoundAtBlock } from '../../utils/utils.js';
import { MinecraftBlockTypes } from '../../minecraft_vanilla_data.js';

world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
    const { block, player, itemStack: item } = event;
    if (!item?.hasTag(FSItemTags.SICKLE)) {
        return;
    }
    if (block.typeId !== MinecraftBlockTypes.Composter) {
        return;
    }
    const fillLevel = getBlockState(block.permutation, MCBlockStates.COMPOSTER_FILL_LEVEL);
    if (fillLevel !== 8) {
        return;
    }
    system.runTimeout(() => {
        spawnItemAtBlock(block, new ItemStack(FSBlocks.COMPOST, 1));
        damageEntityHeldItem(player, calculateItemDamageAmount(item, 1));
        updateBlockState(block, MCBlockStates.COMPOSTER_FILL_LEVEL, 0);
        playSoundAtBlock(block, MCSounds.COMPOST_FILL);
    }, 0);
    event.cancel = true;
});
