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

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

        if(!magicResistanceLevel) {
            player.setDynamicProperty("rustic:magic_resistance",1)
            magicResistanceLevel = 1
        }

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

        if (quality < 0.5){
            player.addEffect("poison",150)
        } else {
            player.setDynamicProperty("rustic:magic_resistance",magicResistanceLevel)
            player.runCommand(`scoreboard players set @s magic_resistance ${durationSecs}`)
        }
      }
    });
    system.runInterval( () => {
        const overworld = world.getDimension("overworld");
        const nether = world.getDimension("nether");
        magicResistance(overworld)
        magicResistance(nether)
    }, 20)
});


export function magicResistance(dimension){
    const allPlayers = dimension.getPlayers();
    for (const player of allPlayers){
        let magicResistanceLevel = player.getDynamicProperty("rustic:magic_resistance")
        if (magicResistanceLevel != 0){
            const playerEffects = player.getEffects()
            for (const effect of playerEffects){
                if (effect.typeId == "poison" || effect.typeId == "fatal_poison" || effect.typeId == "weakness" || effect.typeId == "slowness" || effect.typeId == "mining_fatigue"){
                    player.removeEffect(effect.typeId)
                }
                
            }
        }
    }
    
}