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

system.beforeEvents.startup.subscribe(initEvent => {
    initEvent.itemComponentRegistry.registerCustomComponent('rustic:effect_amplifier', {
      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
        }
        const witherWardLevel = player.getDynamicProperty("rustic:wither_ward")
        const magicResistanceLevel = player.getDynamicProperty("rustic:magic_resistance")
        const fullStomachLevel = player.getDynamicProperty("rustic:full_stomach")

        const playerEffects = player.getEffects()
        let amplifier = 0
        let amplifierLimit = 1
        if (quality == 0.75)amplifierLimit = 2

        if (quality < 0.5){
            player.addEffect('poison', 200);
        }
        else {
            for (const effect of playerEffects){
                if (effect.typeId != "poison" && effect.typeId != "fatal_poison" && effect.typeId != "weakness" && effect.typeId != "slowness" && effect.typeId != "mining_fatigue" && effect.typeId != "wither" && effect.typeId != "nausea" && effect.typeId != "blindness" && effect.typeId != "hunger" && effect.typeId != "darkness" && effect.typeId != "oozing" && effect.typeId != "infested" && effect.typeId != "weaving" && effect.typeId != "wind_charged"){
                    if (effect.amplifier < amplifierLimit){
                        amplifier = effect.amplifier + 1
                        if (effect.duration != -1)player.addEffect(effect.typeId, effect.duration,{ amplifier: amplifier})
                        else{
                            player.runCommand(`effect @s ${effect.typeId} infinite ${amplifier}`)
                        }
                    }
                }
            }
            if (witherWardLevel != 0 && witherWardLevel - 1 < amplifierLimit){
                player.setDynamicProperty("rustic:wither_ward",witherWardLevel + 1)
            }
            if (magicResistanceLevel != 0 && magicResistanceLevel - 1 < amplifierLimit){
                player.setDynamicProperty("rustic:magic_resistance",magicResistanceLevel + 1)
            }
            if (fullStomachLevel != 0 && fullStomachLevel - 1 < amplifierLimit){
                player.setDynamicProperty("rustic:full_stomach",fullStomachLevel + 1)
            }
        }
      }
    });
});


