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

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

        if(!witherWardLevel) {
            player.setDynamicProperty("rustic:wither_ward",1)
            witherWardLevel = 1
        }

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

        if (quality < 0.5){
            player.addEffect("mining_fatigue",300)
        } else {
            player.setDynamicProperty("rustic:wither_ward",witherWardLevel)
            player.runCommand(`scoreboard players set @s wither_ward ${durationSecs}`)
        }
      }
    });
    system.runInterval( () => {
        const overworld = world.getDimension("overworld");
        const nether = world.getDimension("nether");
        witherWard(overworld)
        witherWard(nether)
    }, 20)
});


export function witherWard(dimension){
    const allPlayers = dimension.getPlayers();
    for (const player of allPlayers){
        let witherWardLevel = player.getDynamicProperty("rustic:wither_ward")
        if (witherWardLevel != 0){
            const playerEffects = player.getEffects()
            for (const effect of playerEffects){
                if (effect.typeId == "wither"){
                    player.removeEffect(effect.typeId)
                }
                
            }
        }
    }
    
}