import { world, system } from "@minecraft/server";
import { removeItem, addItem } from "./crushing_tub/crushing_components";

system.beforeEvents.startup.subscribe((initEvent) => {
    initEvent.blockComponentRegistry.registerCustomComponent("rustic:drying_basin", {
        onRandomTick: e => {
            const { block, dimension } = e;
            const itemState = block.permutation.getState("r:item");
            const liquidState = block.permutation.getState("r:liquid");

            if(liquidState > 0 && itemState < 3){
                block.setPermutation(block.permutation.withState("r:liquid",liquidState-1));
                block.setPermutation(block.permutation.withState("r:item",itemState+1));
            }
        },
    });
});

world.beforeEvents.playerInteractWithBlock.subscribe(eventData => {
    const block = eventData.block;
    const item = eventData.itemStack;
    const player = eventData.player;

    if (!block.hasTag("DryingBasin"))return;
    const itemState = block.permutation.getState("r:item");

    if (item == undefined || item.typeId != "rustic:bottle_of_ironberry_juice") {
        if (itemState > 0){
            system.run( () => {
                block.setPermutation(block.permutation.withState("r:item", 0));
                addItem(player,"rustic:iron_dust",itemState)
            })
        }
        return;
    };

    const liquidState = block.permutation.getState("r:liquid");

    if (liquidState == 0){
        if (itemState > 0){
            system.run( () => {
                block.setPermutation(block.permutation.withState("r:item", 0));
                addItem(player,"rustic:iron_dust",itemState)
            })
        }
        system.run( () => {
            block.setPermutation(block.permutation.withState("r:liquid", 3));
            removeItem(player,item,1)
            addItem(player,"minecraft:glass_bottle",1)
        })
    }
    

    eventData.cancel = true
});