import { system, world } from "@minecraft/server";
import { decreaseItemAmountInHand } from "../../helper/utils";
export class CompostableItem {
    constructor(config) {
        this.config = config;
    }
    static registerBehavior(config) {
        const eventItem = new CompostableItem(config);
        this.items.push(eventItem);
    }
    static getItem(id) {
        return CompostableItem.items.find((item) => item.config.id === id);
    }
    static initialize() {
        world.afterEvents.itemUseOn.subscribe((event) => {
            if (event.source.isSneaking)
                return;
            const item = CompostableItem.getItem(event.itemStack.typeId);
            if (!item)
                return;
            const { block } = event;
            if (block.typeId !== "minecraft:composter")
                return;
            const chance = item.config.chance;
            let fillLevel = event.block.permutation.getState("composter_fill_level");
            if (fillLevel === undefined || fillLevel >= 7)
                return;
            system.runTimeout(() => {
                fillLevel = event.block.permutation.getState("composter_fill_level");
                if (fillLevel === undefined || fillLevel >= 7)
                    return;
                decreaseItemAmountInHand(event.source, 1, true);
                event.block.dimension.spawnParticle("minecraft:crop_growth_emitter", event.block.center());
                if (Math.random() > chance) {
                    world.playSound("block.composter.fill", event.block.location);
                    return;
                }
                const newFillLevel = fillLevel + 1;
                event.block.setPermutation(event.block.permutation.withState("composter_fill_level", newFillLevel));
                world.playSound("block.composter.fill_success", event.block.location);
                if (newFillLevel === 7) {
                    system.runTimeout(() => {
                        fillLevel = event.block.permutation.getState("composter_fill_level");
                        if (fillLevel !== 7)
                            return;
                        event.block.setPermutation(event.block.permutation.withState("composter_fill_level", 8));
                        world.playSound("block.composter.ready", event.block.location);
                    }, 20);
                }
            });
        });
    }
}
CompostableItem.items = [];
