import { EquipmentSlot, ItemStack, world } from "@minecraft/server";
import { namespace } from "../../../config/_config";
import { addItemToInventory, getItemInSlot, removeItemFromInventory, } from "../../helper/utils";
export class ItemCrateBlock {
    constructor({ id, item, sound, particle, }) {
        this.id = id;
        this.item = item;
        this.sound = sound;
        this.particle = particle;
    }
    static registerBehavior(config) {
        const block = new ItemCrateBlock(config);
        this.register(block);
    }
    static register(block) {
        ItemCrateBlock.blocks.push(block);
    }
    static initialize() {
        world.beforeEvents.worldInitialize.subscribe((event) => {
            event.blockComponentRegistry.registerCustomComponent(`${namespace}:item_crate`, {
                onPlayerInteract: (event) => {
                    const { block, player } = event;
                    if (!player)
                        return;
                    const item = getItemInSlot(player, EquipmentSlot.Mainhand);
                    const blockBehavior = ItemCrateBlock.blocks.find((b) => b.id === block.typeId);
                    if (!blockBehavior)
                        return;
                    const fillLevel = block.permutation.getState(`${namespace}:fill_level`);
                    if (!fillLevel)
                        return;
                    if (fillLevel < 16) {
                        if (item?.typeId === blockBehavior.item) {
                            block.setPermutation(block.permutation.withState(`${namespace}:fill_level`, fillLevel + 1));
                            if (blockBehavior.sound) {
                                player.playSound(blockBehavior.sound, {
                                    // betweem 1.3 and 1.5
                                    pitch: 1.0 + Math.random() * 0.2,
                                    volume: 0.2,
                                });
                            }
                            removeItemFromInventory(player, blockBehavior.item);
                        }
                    }
                    if (item?.typeId === undefined && fillLevel > 1) {
                        block.setPermutation(block.permutation.withState(`${namespace}:fill_level`, fillLevel - 1));
                        if (blockBehavior.sound) {
                            player.playSound(blockBehavior.sound, {
                                // betweem 0.5 and 0.7
                                pitch: 0.8 + Math.random() * 0.2,
                                volume: 0.2,
                            });
                        }
                        addItemToInventory(player, new ItemStack(blockBehavior.item));
                    }
                },
            });
        });
    }
}
ItemCrateBlock.blocks = [];
