import { system, world } from '@minecraft/server';
export { decrementStack };
const registerCompostables = [
]
class Compostables {
  static getCompostable(item) {
    return registerCompostables[registerCompostables.findIndex(compostable => item === compostable.item)];
  }
  static isCompostable(block) {
    return block.permutation.getState('composter_fill_level') < 7;
  }
  static composting(composter, chance) {
    let composterFillLevel = composter.permutation.getState('composter_fill_level');
    if (Math.random() < chance || composterFillLevel <= 0) {
      composter.setPermutation(composter.permutation.withState('composter_fill_level', ++composterFillLevel));
      if (composterFillLevel === 7) {
        system.runTimeout(() => {
          if (!composter?.isValid() || composter.permutation.getState('composter_fill_level') != composterFillLevel) return;
          composter.setPermutation(composter.permutation.withState('composter_fill_level', 8));
          world.playSound('block.composter.ready', composter.center());
        }, 20);
      }
      world.playSound('block.composter.fill_success', composter.center());
    } else {
      world.playSound('block.composter.fill', composter.center());
    }
    world.playSound('item.bone_meal.use', composter.center(), {pitch: Math.random() * (1.1 - 0.9) + 0.9});
    composter.dimension.spawnParticle('minecraft:crop_growth_emitter', composter.center());
  }
}
function decrementStack(equippable, player = undefined) {
  if (player?.matches({gameMode:'creative'})) return;
  const item = equippable.getEquipment('Mainhand');
  const stack = item.amount;
  if (stack > 1) --item.amount;
  equippable.setEquipment('Mainhand', stack > 1 ? item : null);
}
world.beforeEvents.itemUseOn.subscribe(data => {
  const compostable = Compostables.getCompostable(data.itemStack?.typeId);
  if (compostable && Compostables.isCompostable(data.block) && !data.source?.isSneaking) {
    const player = data.source;
    system.run(() => {
      Compostables.composting(data.block, compostable.chance);
      decrementStack(player.getComponent('equippable'), player);
    });
  }
});