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

system.beforeEvents.startup.subscribe(initEvent => {
    initEvent.itemComponentRegistry.registerCustomComponent('rustic:full_stomach', {
      onConsume: e =>  {
        const item = e.itemStack;
        const itemLore = item.getLore()
        const player = e.source

        let quality = 0.05
        if (itemLore[0]){
            let qualityRegex = /Quality: (\d+(\.\d+)?)/;
            let qualityMatch = itemLore[0].match(qualityRegex);
            if (qualityMatch) {
                quality = qualityMatch[1];
            }
        }
        else{
            quality = 0.75
        }

        let fullStomachLevel = player.getDynamicProperty("rustic:full_stomach")

        if(!fullStomachLevel) {
            player.setDynamicProperty("rustic:full_stomach",1)
            fullStomachLevel = 1
        }

        let durationSecs = 210 + ((quality - 0.5) * 200);
        let durationTicks = 4200 + (((quality - 0.5) * 200) * 20);

        if (quality < 0.5){
            player.addEffect("hunger",100)
        } else {
            player.setDynamicProperty("rustic:full_stomach",fullStomachLevel)
            player.runCommand(`scoreboard players set @s full_stomach ${durationSecs}`)
            player.addEffect("saturation",durationTicks)
        }


      }
    });
});
