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

system.beforeEvents.startup.subscribe(initEvent => {
    initEvent.itemComponentRegistry.registerCustomComponent('rustic:health_boost', {
      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 durationSecs = 210 + ((quality - 0.5) * 200);
        let durationTicks = 4200 + (((quality - 0.5) * 200) * 20);


        const playerEffects = player.getEffects()
        let amplifier = 0

        for (const effect of playerEffects){
            if (effect.typeId == "health_boost"){
                if (effect.amplifier < 4)amplifier = effect.amplifier + 1
            }
        }

        if (quality < 0.5){
            player.addEffect('weakness', 200);
            player.addEffect('mining_fatigue', 200);
            player.addEffect('slowness', 200);
        } else if (quality < 0.74) {
            player.addEffect("health_boost",durationTicks)
        }
        else {
            player.runCommand(`effect @s health_boost infinite ${amplifier}`)
        }
      }
    });
});


