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

system.beforeEvents.startup.subscribe(initEvent => {
    initEvent.itemComponentRegistry.registerCustomComponent('rustic:increase_duration', {
      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 worldScoreboard = world.scoreboard

        const witherWardLevel = player.getDynamicProperty("rustic:wither_ward")
        const magicResistanceLevel = player.getDynamicProperty("rustic:magic_resistance")
        const fullStomachLevel = player.getDynamicProperty("rustic:full_stomach")

        const fullStomachObjective = worldScoreboard.getObjective("full_stomach")
        const magicResistanceObjective = worldScoreboard.getObjective("magic_resistance")
        const witherWardObjective = worldScoreboard.getObjective("wither_ward")

        const playerEffects = player.getEffects()
        let duration = 1200
        let durationLimit = 9600
        if (quality == 0.75)durationLimit = 12000

        if (quality < 0.5){
            player.addEffect('slowness', 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.duration < durationLimit){
                        if (effect.duration + duration > durationLimit){
                            player.addEffect(effect.typeId, durationLimit)
                        }
                        else{
                            player.addEffect(effect.typeId, effect.duration + duration)
                        }
                    }
                }
            }
            if (witherWardLevel != 0 && (witherWardObjective.getScore(player) * 20) < durationLimit){
                witherWardObjective.addScore(player,duration)
            }
            if (magicResistanceLevel != 0 && magicResistanceObjective.getScore(player) * 20 < durationLimit){
                magicResistanceObjective.addScore(player,duration)
            }
            if (fullStomachLevel != 0 && fullStomachObjective.getScore(player) * 20 < durationLimit){
                fullStomachObjective.addScore(player,duration)
            }
        }
      }
    });
});


