import {getPlayerLevel, getPlayerExp, checkRankUpLevel, setPlayerExp, setPlayerLevel, getExpFromLevel, rankUpFromLevel} from "../logic/combatmastery"

import { world } from "@minecraft/server";

world.afterEvents.itemUse.subscribe((event) => {
    const { itemStack, source } = event;
    if (!source || !itemStack) return;

    if (itemStack.typeId === "msft:green_gemstone") {
        const inventory = source.getComponent("minecraft:inventory")?.container;
        if (!inventory) return;


        let slotItem = inventory.getItem(0);
        if (slotItem && slotItem.typeId === itemStack.typeId) {
            if (slotItem.amount > 1) {
                slotItem.amount -= 1; 
                inventory.setItem(0, slotItem);
            } else {
                inventory.setItem(0, undefined); 
            }
        }

        let location = {
            x: source.location.x + 1,
            y: source.location.y + 1.5,
            z: source.location.z
        }
        source.dimension.spawnParticle("msft_bc:consumable", location);
        
        const exp = getPlayerExp(source);
        const level = getPlayerLevel(source);
        if(!checkRankUpLevel(source, exp, level)) {
            const newExp = exp + 50;

            setPlayerExp(source, newExp);
        }
    }
});
