import { world, ItemStack, system, GameMode, BlockPermutation } from "@minecraft/server";
import { vanillaFoods } from "./data";


system.beforeEvents.startup.subscribe((initEvent) => {
    initEvent.blockComponentRegistry.registerCustomComponent("rustic:oiled_food", {
        onPlayerInteract: e => {
            const { player, block, dimension } = e;

            const liquidType = block.permutation.getState("r:type");
            const liquidLevel = block.permutation.getState("r:fill");
            const equipment = player.getComponent('equippable');
            const selectedItem = equipment.getEquipment('Mainhand');
            
            if ( !selectedItem || liquidType != 8 || liquidLevel < 1 || selectedItem.hasTag("rustic:is_bottle") || (!vanillaFoods.includes(selectedItem?.typeId) && !selectedItem?.hasComponent("minecraft:food"))) return;

            let itemLore = selectedItem.getLore()
            if (itemLore.includes("§r§2Olive Oiled§r"))return;
            itemLore.push("§r§2Olive Oiled§r")
            let amountOfItems;

            if (selectedItem.amount >= liquidLevel){
                amountOfItems = liquidLevel
                block.setPermutation(block.permutation.withState("r:type", 0));
            } else amountOfItems = selectedItem.amount
            
            const newItem = new ItemStack(selectedItem.typeId, amountOfItems)
            newItem.setLore(itemLore)

            block.setPermutation(block.permutation.withState("r:fill", liquidLevel - amountOfItems));
            player.getComponent("inventory").container.addItem(newItem);

            if (!(selectedItem.amount - amountOfItems))equipment.setEquipment('Mainhand', undefined);
            else {
                selectedItem.amount -= amountOfItems
                equipment.setEquipment('Mainhand', selectedItem);
            }
            
        },
    });
});



world.afterEvents.itemCompleteUse.subscribe(eventData => {
    const {itemStack, source} = eventData;
    if (vanillaFoods.includes(itemStack.typeId) || itemStack.hasComponent("minecraft:food")) {
        if (!itemStack.getLore().includes("§r§2Olive Oiled§r"))return;
        const hungerComponent = source.getComponent("minecraft:player.hunger")
        const saturationComponent = source.getComponent("minecraft:player.saturation")
        let hungerAdd = hungerComponent.currentValue
        let saturationAdd = saturationComponent.currentValue
        if (hungerAdd + 2 > hungerComponent.effectiveMax) hungerAdd += hungerComponent.effectiveMax - hungerAdd
        else hungerAdd += 2
        if (saturationAdd + 4 > saturationComponent.effectiveMax) hungerAdd += saturationComponent.effectiveMax - saturationAdd
        else saturationAdd += 4
        hungerComponent.setCurrentValue(hungerAdd)
        saturationComponent.setCurrentValue(saturationAdd)
    }
})