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

system.beforeEvents.startup.subscribe(initEvent => {
    initEvent.itemComponentRegistry.registerCustomComponent('rustic:inebriation', {
      onConsume: e =>  {
        const item = e.itemStack;
        const itemLore = item.getLore()
        const player = e.source;

        //Obtain quality
        let quality = 0.05
        if (itemLore[0]){
            let qualityRegex = /Quality: (\d+(\.\d+)?)/;
            let qualityMatch = itemLore[0].match(qualityRegex);
            if (qualityMatch) {
                quality = qualityMatch[1];  // Convertir a decimal
            }
        }
        else{
            quality = 0.75
        }

        let inebriationLevel = player.getDynamicProperty("rustic:inebriation")

        if(!inebriationLevel) {
            player.setDynamicProperty("rustic:inebriation",0)
            inebriationLevel = 0
        }

        //Effect
        let drunkProbability = 0.3;

        // Probability based on quality
        if (quality < 0.2) {
            drunkProbability += 0.4;
        } 
        else if (quality < 0.5) {
            drunkProbability += 0.3;
        }
        else if (quality < 0.7) {
            drunkProbability += 0.1;
        }

        let drunkRoll = Math.random();

        if (drunkRoll < drunkProbability) {
            let newInebriationLevel = inebriationLevel;

            if (inebriationLevel < 4){
                newInebriationLevel++
            }
            if (newInebriationLevel !== inebriationLevel) {
                inebriationLevel = newInebriationLevel;
                player.setDynamicProperty("rustic:inebriation", inebriationLevel);
            }
            if (newInebriationLevel > 2){
                player.runCommand("scoreboard players set @s inebriation 210")
            }
            else{
                player.runCommand("scoreboard players set @s inebriation 600")
            }

            if (newInebriationLevel >= 3){
                player.addEffect("blindness",4200)
                player.addEffect("slowness",4200)
            }
            if ( newInebriationLevel == 4){
                player.addEffect("blindness",4200)
                player.addEffect("slowness",4200,{ amplifier: 1})
                player.addEffect("nausea",4200,{ amplifier: 1})
            }
            
        }

        

      }
    });
    system.run( () => {
        const dimension = world.getDimension("overworld");
        dimension.runCommand("scoreboard objectives add inebriation dummy")
        dimension.runCommand("scoreboard objectives add full_stomach dummy")
        dimension.runCommand("scoreboard objectives add magic_resistance dummy")
        dimension.runCommand("scoreboard objectives add wither_ward dummy")
    })
    

});


world.afterEvents.itemCompleteUse.subscribe(initEvent =>{
    const item = initEvent.itemStack;
    const player = initEvent.source;
    const worldScoreboard = world.scoreboard
    const inebriationObjective = worldScoreboard.getObjective("inebriation")
    const playerDisplay = player.onScreenDisplay
    if (item.typeId == "minecraft:potion"){
        const inebriationProperty = player.getDynamicProperty("rustic:inebriation")

        let random = Math.random();

        if (random < 0.5){
            if (inebriationProperty != 0){
                if (inebriationProperty == 3){
                    player.removeEffect("blindness")
                    player.removeEffect("slowness")
                }
                if (inebriationProperty == 4){
                    player.removeEffect("nausea")
                }
                if (inebriationProperty == 1){
                    inebriationObjective.setScore(player,0)
                    player.setDynamicProperty("rustic:inebriation",0);
                    playerDisplay.setTitle("empty")
                }
                
                player.setDynamicProperty("rustic:inebriation", inebriationProperty - 1)
            }
        }        
    }
    else if (item.typeId == "minecraft:milk_bucket"){
        const worldScoreboard = world.scoreboard
        removeRusticEffects(player,worldScoreboard)
    }
});

world.beforeEvents.itemUse.subscribe(initEvent => {
    const item = initEvent.itemStack;
    const player = initEvent.source;

    if (item.typeId != "minecraft:milk_bucket" && item.typeId != "rustic:bottle_of_milk") return;

    const inebriationProperty = player.getDynamicProperty("rustic:inebriation")
    const allEfects = player.getEffects()

    if (!allEfects || inebriationProperty < 3) return;

    for (const effect of allEfects){
        if (effect && (effect.typeId == "nausea" || effect.typeId == "slowness" || effect.typeId == "blindness") && inebriationProperty > 2){
            initEvent.cancel = true
        }
    }
});

world.afterEvents.entityDie.subscribe(initEvent => {
    const entity = initEvent.deadEntity
    if (entity.typeId != "minecraft:player") return;
    const playerDisplay = entity.onScreenDisplay
    const worldScoreboard = world.scoreboard

    const inebriationProperty = entity.getDynamicProperty("rustic:inebriation")
    const fullStomachProperty = entity.getDynamicProperty("rustic:full_stomach")
    const magicResistanceProperty = entity.getDynamicProperty("rustic:magic_resistance")
    const witherWardProperty = entity.getDynamicProperty("rustic:wither_ward")

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

    if (fullStomachProperty != 0){
        entity.setDynamicProperty("rustic:full_stomach",0)
        fullStomachObjective.setScore(entity,0)
        playerDisplay.setTitle("empty")
        
    }
    if (magicResistanceProperty != 0){
        entity.setDynamicProperty("rustic:magic_resistance",0)
        magicResistanceObjective.setScore(entity,0)
        playerDisplay.setTitle("empty")
    }
    if (witherWardProperty != 0){
        entity.setDynamicProperty("rustic:wither_ward",0)
        witherWardObjective.setScore(entity,0)
        playerDisplay.setTitle("empty")
    }
    if (inebriationProperty != 0){
        entity.setDynamicProperty("rustic:inebriation",0)
        inebriationObjective.setScore(entity,0)
        playerDisplay.setTitle("empty")
    }
})


system.runInterval( () => {
    const overworld = world.getDimension("overworld");
    const nether = world.getDimension("nether");
    rusticEffects(overworld)
    rusticEffects(nether)
}, 20)

export function removeRusticEffects(player,worldScoreboard){
    const playerDisplay = player.onScreenDisplay
    const fullStomachProperty = player.getDynamicProperty("rustic:full_stomach")
    const magicResistanceProperty = player.getDynamicProperty("rustic:magic_resistance")
    const witherWardProperty = player.getDynamicProperty("rustic:wither_ward")
    const fullStomachObjective = worldScoreboard.getObjective("full_stomach")
    const magicResistanceObjective = worldScoreboard.getObjective("magic_resistance")
    const witherWardObjective = worldScoreboard.getObjective("wither_ward")
    if (fullStomachProperty != 0){
        player.setDynamicProperty("rustic:full_stomach",0)
        fullStomachObjective.setScore(player,0)
        playerDisplay.setTitle("empty")
    }
    if (magicResistanceProperty != 0){
        player.setDynamicProperty("rustic:magic_resistance",0)
        magicResistanceObjective.setScore(player,0)
        playerDisplay.setTitle("empty")
    }
    if (witherWardProperty != 0){
        player.setDynamicProperty("rustic:wither_ward",0)
        witherWardObjective.setScore(player,0)
        playerDisplay.setTitle("empty")
    }
}

export function rusticEffects(dimension){
    const worldScoreboard = world.scoreboard
    const allPlayers = dimension.getPlayers();
    for (const player of allPlayers){
        const inebriationObjective = worldScoreboard.getObjective("inebriation")
        const fullStomachObjective = worldScoreboard.getObjective("full_stomach")
        const magicResistanceObjective = worldScoreboard.getObjective("magic_resistance")
        const witherWardObjective = worldScoreboard.getObjective("wither_ward")

        const playerDisplay = player.onScreenDisplay
        if (inebriationObjective.hasParticipant(player)){
            const playerScore = inebriationObjective.getScore(player)
            if (playerScore == 1){
                player.setDynamicProperty("rustic:inebriation",0);
                playerDisplay.setTitle("empty")
            }
            if (playerScore > 0)inebriationObjective.setScore(player,playerScore - 1)
        }
        if (fullStomachObjective.hasParticipant(player)){
            const playerScore = fullStomachObjective.getScore(player)
            if (playerScore == 1){
                player.setDynamicProperty("rustic:full_stomach",0);
                playerDisplay.setTitle("empty")
            }
            if (playerScore > 0)fullStomachObjective.setScore(player,playerScore - 1)
        }
        if (magicResistanceObjective.hasParticipant(player)){
            const playerScore = magicResistanceObjective.getScore(player)
            if (playerScore == 1){
                player.setDynamicProperty("rustic:magic_resistance",0);
                playerDisplay.setTitle("empty")
            }
            if (playerScore > 0)magicResistanceObjective.setScore(player,playerScore - 1)
        }
        if (witherWardObjective.hasParticipant(player)){
            const playerScore = witherWardObjective.getScore(player)
            if (playerScore == 1){
                player.setDynamicProperty("rustic:wither_ward",0);
                playerDisplay.setTitle("empty")
            }
            if (playerScore > 0)witherWardObjective.setScore(player,playerScore - 1)
        }
        let titleEffects = "empty;"
        const inebriationProperty = player.getDynamicProperty("rustic:inebriation")
        const fullStomachProperty = player.getDynamicProperty("rustic:full_stomach")
        const magicResistanceProperty = player.getDynamicProperty("rustic:magic_resistance")
        const witherWardProperty = player.getDynamicProperty("rustic:wither_ward")
        if (inebriationProperty != 0 && inebriationProperty){
            titleEffects += "inebriation" + inebriationProperty + ";"
        }
        if (fullStomachProperty != 0 && fullStomachProperty){
            titleEffects += "full_stomach" + fullStomachProperty + ";"
        }
        if (magicResistanceProperty != 0 && magicResistanceProperty){
            titleEffects += "magic_resistance" + magicResistanceProperty + ";"
        }
        if (witherWardProperty != 0 && witherWardProperty){
            titleEffects += "wither_ward" + witherWardProperty + ";"
        }

        if (titleEffects)playerDisplay.setTitle(titleEffects)        
    }
}

