import { world, ItemStack, system } from "@minecraft/server";
import Timer from "../timer/timerClass";

export let totalTime = 600;

const brewingSlots = [2,4,7,9,10,11,12,13,14]


system.beforeEvents.startup.subscribe(eventData => {
    eventData.blockComponentRegistry.registerCustomComponent("rustic:brewing_barrel", {
        beforeOnPlayerPlace: e => {
            const { player, block, face, permutationToPlace, dimension } = e;
            const blockLocation = block.center()
            system.run(() => {
                const brewingEntity = block.dimension.spawnEntity("rustic:brewing_barrel_ui", {x: blockLocation.x, y: block.location.y, z: blockLocation.z});
                brewingEntity.nameTag = `brewing_barrel`
                //Dynamic properties for system and UI management
                brewingEntity.setDynamicProperty("catalyst","false;name;0.05")
                brewingEntity.setDynamicProperty("liquid_container","false;name;0.05;0")
                brewingEntity.setDynamicProperty("brewing",false)
                brewingEntity.setDynamicProperty("result_container","false;name;0.05;0")

                let brewingContainer = brewingEntity.getComponent('inventory').container;

                const emptyItem = new ItemStack("rustic:brewing_placeholder", 1);
                emptyItem.nameTag = "none"
                
                for (const slot of brewingSlots) {
                    brewingContainer.setItem(slot,emptyItem)
                }
            })
            
            
            
        },
        onPlayerBreak: e => {
            const { player, block, dimension } = e;
            const entities = dimension.getEntities({type: "rustic:brewing_barrel_ui", location: block.center(), maxDistance: 1})
            for (const entity of entities){
                let brewingContainer = entity.getComponent('inventory').container;
                for (const slot of brewingSlots) {
                    brewingContainer.setItem(slot,undefined)
                }
            }
        },
        onTick: e => {
            const block = e.block;
            const dimension = e.dimension;

            const entities = dimension.getEntities({type: "rustic:brewing_barrel_ui", location: block.center(), maxDistance: 1})
            for (const entity of entities){
                let brewingContainer = entity.getComponent('inventory').container;

                //Catalyst Properties
                let catalystDynamicProperty = entity.getDynamicProperty("catalyst")

                let catalystParts = catalystDynamicProperty.split(";");

                //Propiedades del catalizador
                let catalystBoolValue = catalystParts[0] === "true";
                let catalystName = catalystParts[1];
                //let catalystQuality = parseFloat(catalystParts[2]);
                let catalystQuality = catalystParts[2];
                //Catalyst Input
                let catalysInput = brewingContainer.getItem(0);
                let catalystOutput = brewingContainer.getItem(1);
                //Liquid container
                let liquidInput = brewingContainer.getItem(3);
                let liquidOutput = brewingContainer.getItem(5);
                //Result Container
                let resultInput = brewingContainer.getItem(6);
                let resultOutput = brewingContainer.getItem(8);

                if (!catalystBoolValue && catalysInput){
                    if (catalysInput && catalystLiquids[catalysInput.typeId] && catalystLiquids[catalysInput.typeId].quality){
                        if (catalystOutput && catalystOutput.typeId != catalystLiquids[catalysInput.typeId].output)return;
                        const outputItem = new ItemStack(catalystLiquids[catalysInput.typeId].output, 1);
                        const catalystIcon = new ItemStack("rustic:brewing_placeholder", 1);
                        catalystIcon.nameTag = catalystLiquids[catalysInput.typeId].texture

                        //Catalyst Icon
                        brewingContainer.setItem(10,catalystIcon)
                        //Catalyst Output
                        
                        if (catalystOutput && catalystOutput.typeId == catalystLiquids[catalysInput.typeId].output){
                            catalystOutput.amount += 1
                            brewingContainer.setItem(1,catalystOutput)
                        }
                        else{
                            brewingContainer.setItem(1,outputItem)
                        }
                        let qualityLore = catalysInput.getLore()
                        let quality = 0.75
                        if (qualityLore[0]){
                            let qualityRegex = /Quality: (\d+(\.\d+)?)/;
                            let qualityMatch = qualityLore[0].match(qualityRegex);
                            if (qualityMatch) {
                                quality = qualityMatch[1];  // Convertir a decimal
                            }
                        }
                        
                        //console.warn(quality)
                        entity.setDynamicProperty("catalyst", "true;" + catalystLiquids[catalysInput.typeId].name + ";" + quality)
                        //console.warn("Catalizador:" + catalystLiquids[catalysInput.typeId].name)

                        if (catalysInput.amount == 1){
                            brewingContainer.setItem(0,undefined)
                        }
                        else if (catalysInput.amount > 1) {
                            catalysInput.amount -= 1;
                            brewingContainer.setItem(0,catalysInput)
                        }
                    }
                }
                else if(catalystBoolValue && catalysInput){
                    if (catalysInput && catalysInput.typeId == catalystLiquids[catalystName].output){
                        if (catalystOutput && catalystOutput.typeId != catalystName)return;
                        let quality;
                        if (catalystOutput)quality = getLiquidQuality(catalystOutput)
                        if (catalystOutput && quality != catalystQuality)return;
                        const outputItem = new ItemStack(catalystName, 1);
                        outputItem.setLore(["§r§6Quality: " + catalystQuality])
                        if (catalystOutput && catalystOutput.typeId == catalystName){
                            catalystOutput.amount += 1
                            brewingContainer.setItem(1,catalystOutput)
                        }
                        else{
                            brewingContainer.setItem(1,outputItem)
                        }
                        brewingContainer.setItem(10,undefined)

                        entity.setDynamicProperty("catalyst", "false;" + "name" + ";0.05")


                        if (catalysInput.amount == 1){
                            brewingContainer.setItem(0,undefined)
                        }
                        else if (catalysInput.amount > 1) {
                            catalysInput.amount -= 1;
                            brewingContainer.setItem(0,catalysInput)
                        }
                    }
                }

                let liquidDynamicProperty = entity.getDynamicProperty("liquid_container")
                let liquidParts = liquidDynamicProperty.split(";");
                //Propiedades del contenedor liquido
                let liquidBoolValue = liquidParts[0] === "true";
                let liquidName = liquidParts[1];
                //let catalystQuality = parseFloat(liquidParts[2]);
                let liquidQuality = liquidParts[2];
                let liquidLevel = liquidParts[3];

                if (liquidInput && inputLiquids[liquidInput.typeId] && parseInt(liquidLevel,10) < 3){
                    if (liquidOutput && liquidOutput.typeId != inputLiquids[liquidInput.typeId].output)return;
                    if ((parseInt(inputLiquids[liquidInput.typeId].level) + parseInt(liquidLevel,10)) > 3) return;
                    const outputItem = new ItemStack(inputLiquids[liquidInput.typeId].output, 1);
                    const liquidIcon = new ItemStack("rustic:brewing_placeholder", 1);
                    let newLevel = (parseInt(liquidLevel,10) + inputLiquids[liquidInput.typeId].level).toString()
                    liquidIcon.nameTag = inputLiquids[liquidInput.typeId].texture + "_" + newLevel

                    //Catalyst Icon
                    brewingContainer.setItem(11,liquidIcon)

                    if (liquidOutput && liquidOutput.typeId == inputLiquids[liquidInput.typeId].output){
                        liquidOutput.amount += 1
                        brewingContainer.setItem(5,liquidOutput)
                    }
                    else{
                        brewingContainer.setItem(5,outputItem)
                    }

                    let quality = 0.00
                    //console.warn(quality)
                    entity.setDynamicProperty("liquid_container", "true;" + inputLiquids[liquidInput.typeId].name + ";" + quality + ";" + newLevel)
                    //console.warn("Catalizador:" + inputLiquids[catalysInput.typeId].name)

                    if (liquidInput.amount == 1){
                        brewingContainer.setItem(3,undefined)
                    }
                    else if (liquidInput.amount > 1) {
                        liquidInput.amount -= 1;
                        brewingContainer.setItem(3,liquidInput)
                    }
                }
                else if (liquidInput && liquidBoolValue && parseInt(liquidLevel,10) >= 1 && liquidInput.typeId == inputLiquids[liquidName].output){
                    if (liquidOutput && (liquidOutput.typeId != liquidName))return;
                    
                    let liquidIcon = brewingContainer.getItem(11);
                    let newLevel = (parseInt(liquidLevel,10) - inputLiquids[liquidName].level).toString()
                    const outputItem = new ItemStack(liquidName, 1);
                    if (inputLiquids[liquidName].quality){
                        outputItem.setLore(["§r§6Quality: " + catalystQuality])
                    }
                    if(parseInt(liquidLevel,10) > parseInt(inputLiquids[liquidName].level)){
                        liquidIcon.nameTag = liquidIcon.nameTag.slice(0, -1) + (parseInt(liquidIcon.nameTag.slice(-1)) - 1).toString()
                    }
                    else if (parseInt(inputLiquids[liquidName].level) == parseInt(liquidLevel,10)){
                        liquidIcon.nameTag = liquidIcon.nameTag.slice(0, -2)
                        liquidBoolValue = false
                    }

                    brewingContainer.setItem(11,liquidIcon)

                    if (liquidOutput && liquidOutput.typeId == liquidName){
                        liquidOutput.amount += 1
                        brewingContainer.setItem(5,liquidOutput)
                    }
                    else{
                        brewingContainer.setItem(5,outputItem)
                    }

                    entity.setDynamicProperty("liquid_container", liquidBoolValue.toString() + ";" + inputLiquids[liquidName].name + ";" + liquidQuality + ";" + newLevel)
                    
                    if (liquidInput.amount == 1){
                        brewingContainer.setItem(3,undefined)
                    }
                    else if (liquidInput.amount > 1) {
                        liquidInput.amount -= 1;
                        brewingContainer.setItem(3,liquidInput)
                    }
                }
                let bubblesSlot = brewingContainer.getItem(14);
                let arrowSlot = brewingContainer.getItem(13);
                let brewingDynamicProperty = entity.getDynamicProperty("brewing")

                
                let outputDynamicProperty = entity.getDynamicProperty("result_container")
                let outputParts = outputDynamicProperty.split(";");

                let outputBoolValue = outputParts[0] === "true";
                let OutputName = outputParts[1];
                let OutputQuality = outputParts[2];
                let OutputLevel = outputParts[3];

                if (resultInput && outputBoolValue && parseInt(OutputLevel,10) >= 1 && resultInput.typeId == catalystLiquids[OutputName].output){
                    if (resultOutput && resultOutput.typeId != OutputName)return;
                    let quality;
                    if (resultOutput)quality = getLiquidQuality(resultOutput)
                    if (resultOutput && quality != OutputQuality)return;
                    let outputIcon = brewingContainer.getItem(12);
                    let newLevel = (parseInt(OutputLevel,10) - catalystLiquids[OutputName].level).toString()
                    const outputItem = new ItemStack(OutputName, 1);
                    if (catalystLiquids[OutputName].quality){
                        outputItem.setLore(["§r§6Quality: " + OutputQuality])
                    }
                    if(parseInt(OutputLevel,10) > 1){
                        outputIcon.nameTag = outputIcon.nameTag.slice(0, -1) + (parseInt(outputIcon.nameTag.slice(-1)) - 1).toString()
                    }
                    else{
                        outputIcon.nameTag = outputIcon.nameTag.slice(0, -2)
                        outputBoolValue = false
                    }
                    
                    brewingContainer.setItem(12,outputIcon)

                    if (resultOutput && resultOutput.typeId == OutputName){
                        resultOutput.amount += 1
                        brewingContainer.setItem(8,resultOutput)
                    }
                    else{
                        brewingContainer.setItem(8,outputItem)
                    }

                    entity.setDynamicProperty("result_container", outputBoolValue.toString() + ";" + catalystLiquids[OutputName].name + ";" + OutputQuality + ";" + newLevel)
                    
                    if (resultInput.amount == 1){
                        brewingContainer.setItem(6,undefined)
                    }
                    else if (resultInput.amount > 1) {
                        resultInput.amount -= 1;
                        brewingContainer.setItem(6,resultInput)
                    }
                }

                //Start Brewing Process
                if (!brewingDynamicProperty && liquidBoolValue && (!bubblesSlot || bubblesSlot.nameTag == "none") && (!arrowSlot || arrowSlot.nameTag == "none") && !outputBoolValue){
                    if (catalystBoolValue && inputLiquids[liquidName] && inputLiquids[liquidName].brewed != catalystLiquids[catalystName].name)return;
                    const bubblesAnim = new ItemStack("rustic:brewing_placeholder", 1);
                    bubblesAnim.nameTag = "brewing_bubbles_anim"
                    //Catalyst Icon
                    brewingContainer.setItem(14,bubblesAnim)
                    
                    if (!brewingDynamicProperty){
                        entity.setDynamicProperty("brewing", true)
                        brewingDynamicProperty = true
                    }

                    let stateChangeInterval = totalTime / 24;
                    let timeHolder = Timer.set(totalTime, "seconds");
                    let counter = 1;
                    let intervalId;
                    let arrowStateTime = 0;

                    //Temporizador
                    if (brewingDynamicProperty && liquidBoolValue){
                        const arrowAnim = new ItemStack("rustic:brewing_placeholder", 1);
                        intervalId = system.runInterval(() => {
                            let isExpired = Timer.hasExpired(timeHolder);
                            brewingDynamicProperty = entity.getDynamicProperty("brewing")
                            let liquidDynamicProperty = entity.getDynamicProperty("liquid_container")
                            let liquidParts = liquidDynamicProperty.split(";");
                            let liquidBoolValue = liquidParts[0] === "true";
                            let liquidName = liquidParts[1];
                            let liquidLevel = liquidParts[3];

                            let catalystDynamicProperty = entity.getDynamicProperty("catalyst")
                            let catalystParts = catalystDynamicProperty.split(";");

                            //Propiedades del catalizador
                            let catalystBoolValue = catalystParts[0] === "true";
                            let catalystName = catalystParts[1];
                            
    

                            if (!isExpired && brewingDynamicProperty) {
                                // Manejo del estado de la flecha: cambiar cada 25 segundos
                                
                                arrowStateTime++;
                                if (arrowStateTime >= stateChangeInterval) {  // * 20 para convertir segundos a ticks
                                    if (counter <= 24) {
                                        let arrowString = "large_arrow_full_" + counter;
                                        arrowAnim.nameTag = arrowString;
                                        brewingContainer.setItem(13, arrowAnim);
                                        counter++;  // Incrementamos el contador
                                    }
                                    arrowStateTime = 0;  // Reiniciamos el tiempo para el próximo cambio de estado
                                }
                            } 
    
                            if (!brewingDynamicProperty || !liquidBoolValue || (catalystBoolValue && (inputLiquids[liquidName].brewed != catalystLiquids[catalystName].name))) {
                                arrowAnim.nameTag = "none"
                                brewingContainer.setItem(13,arrowAnim)
                                brewingContainer.setItem(14,arrowAnim)
                                entity.setDynamicProperty("brewing", false)
                                //console.warn("Se detuvo")
                                system.clearRun(intervalId);
                            }

                            if(isExpired){
                                arrowAnim.nameTag = "none"
                                brewingContainer.setItem(11,arrowAnim)
                                brewingContainer.setItem(13,arrowAnim)
                                brewingContainer.setItem(14,arrowAnim)
                                //console.warn("Fermentado")
                                entity.setDynamicProperty("brewing", false)

                                entity.dimension.playSound("random.potion.brewed",entity.location)

                                let catalystDynamicProperty = entity.getDynamicProperty("catalyst")
                                let catalystParts = catalystDynamicProperty.split(";");
                                let catalystQuality = parseFloat(catalystParts[2]);
                                let randomQualityWithCatalyst = calculateRandomQuality(catalystQuality);

                                //console.warn(randomQualityWithCatalyst)
                                //console.warn(liquidLevel)

                                let liquidOutputIcon = inputLiquids[liquidName].texture_wine + "_" + liquidLevel

                                arrowAnim.nameTag = liquidOutputIcon
                                //console.warn(liquidOutputIcon)
                                brewingContainer.setItem(12,arrowAnim)


                                entity.setDynamicProperty("liquid_container", "false;name;0.05;0")

                                entity.setDynamicProperty("result_container", "true;" + inputLiquids[liquidName].brewed + ";" + randomQualityWithCatalyst + ";" + liquidLevel)

                                system.clearRun(intervalId);
                            }
                        }, 20);
                    }
                    
                }
                else if (!liquidBoolValue && bubblesSlot && bubblesSlot.nameTag == "brewing_bubbles_anim"){
                    bubblesSlot.nameTag = "none"
                    brewingContainer.setItem(14,bubblesSlot)
                    brewingContainer.setItem(13,bubblesSlot)
                    entity.setDynamicProperty("brewing", false)
                    
                }
                if (catalystBoolValue && catalystLiquids[liquidName] && catalystLiquids[liquidName].brewed != catalystLiquids[catalystName].name && bubblesSlot && bubblesSlot.nameTag == "brewing_bubbles_anim"){
                    bubblesSlot.nameTag = "none"
                    brewingContainer.setItem(14,bubblesSlot)
                    brewingContainer.setItem(13,bubblesSlot)
                    entity.setDynamicProperty("brewing", false)
                    
                }

                
            }
        },
    });
});

//ticking 6,6


export function getRandomWithBias(min, max, biasPower) {
    let random = Math.random();
    return min + Math.pow(random, biasPower) * (max - min);
}

export function calculateRandomQuality(catalyst) {
    let min = 0.05;
    let max = 0.75;
    let biasPower = 3;

    if (catalyst) {
        min = catalyst - 0.01;
        max = catalyst + 0.04;
        if (max > 0.75) max = 0.75;
        if (min < 0.05) min = 0.05;
    }
    let randomQuality = getRandomWithBias(min, max, biasPower);

    return parseFloat(randomQuality.toFixed(2));
}

export function getLiquidQuality(catalysInput){
    let qualityLore = catalysInput.getLore()
    let quality = 0.05
    if (qualityLore[0]){
        let qualityRegex = /Quality: (\d+(\.\d+)?)/;
        let qualityMatch = qualityLore[0].match(qualityRegex);
        if (qualityMatch) {
            quality = qualityMatch[1];  // Convertir a decimal
        }
    }
    return quality;
}


export const catalystLiquids = {
    "rustic:wildberry_wine_bottle":{
        name: "rustic:wildberry_wine_bottle",
        texture: "wildberry_wine",
        output: "minecraft:glass_bottle",
        level: 1,
        quality: true,
        brewed: "rustic:wildberry_wine_bottle"
    },
    "rustic:ironberry_wine_bottle":{
        name: "rustic:ironberry_wine_bottle",
        texture: "ironberry_wine",
        output: "minecraft:glass_bottle",
        level: 1,
        quality: true,
        brewed: "rustic:ironberry_wine_bottle"
    },
    "rustic:wine_bottle":{
        name: "rustic:wine_bottle",
        texture: "wine",
        output: "minecraft:glass_bottle",
        level: 1,
        quality: true,
        brewed: "rustic:wine_bottle"
    },
    "rustic:ale_bottle":{
        name: "rustic:ale_bottle",
        texture: "ale",
        output: "minecraft:glass_bottle",
        level: 1,
        quality: true,
        brewed: "rustic:ale_bottle"
    },
    "rustic:cider_bottle":{
        name: "rustic:cider_bottle",
        texture: "cider",
        output: "minecraft:glass_bottle",
        level: 1,
        quality: true,
        brewed: "rustic:cider_bottle"
    },
    "rustic:mead_bottle":{
        name: "rustic:mead_bottle",
        texture: "mead",
        output: "minecraft:glass_bottle",
        level: 1,
        quality: true,
        brewed: "rustic:mead_bottle"
    }
}

export const inputLiquids = {
    "rustic:bottle_of_wildberry_juice":{
        name: "rustic:bottle_of_wildberry_juice",
        texture: "wildberry_juice",
        texture_wine: "wildberry_wine",
        output: "minecraft:glass_bottle",
        variant: "rustic:wildberry_juice_bucket",
        level: 1,
        quality: false,
        brewed: "rustic:wildberry_wine_bottle"
    },
    "rustic:wildberry_juice_bucket":{
        name: "rustic:wildberry_juice_bucket",
        texture: "wildberry_juice",
        texture_wine: "wildberry_wine",
        output: "minecraft:bucket",
        variant: "rustic:bottle_of_wildberry_juice",
        level: 3,
        quality: false,
        brewed: "rustic:wildberry_wine_bottle"
    },
    "rustic:bottle_of_ironberry_juice":{
        name: "rustic:bottle_of_ironberry_juice",
        texture: "ironberry_juice",
        texture_wine: "ironberry_wine",
        output: "minecraft:glass_bottle",
        level: 1,
        quality: false,
        brewed: "rustic:ironberry_wine_bottle"
    },
    "rustic:ironberry_juice_bucket":{
        name: "rustic:ironberry_juice_bucket",
        texture: "ironberry_juice",
        texture_wine: "ironberry_wine",
        output: "minecraft:bucket",
        level: 3,
        quality: false,
        brewed: "rustic:ironberry_wine_bottle"
    },
    "rustic:bottle_of_grape_juice":{
        name: "rustic:bottle_of_grape_juice",
        texture: "grape_juice",
        texture_wine: "wine",
        output: "minecraft:glass_bottle",
        level: 1,
        quality: false,
        brewed: "rustic:wine_bottle"
    },
    "rustic:grape_juice_bucket":{
        name: "rustic:grape_juice_bucket",
        texture: "grape_juice",
        texture_wine: "wine",
        output: "minecraft:bucket",
        level: 3,
        quality: false,
        brewed: "rustic:wine_bottle"
    },
    "rustic:bottle_of_ale_wort":{
        name: "rustic:bottle_of_ale_wort",
        texture: "ale_wort",
        texture_wine: "ale",
        output: "minecraft:glass_bottle",
        level: 1,
        quality: false,
        brewed: "rustic:ale_bottle"
    },
    "rustic:ale_wort_bucket":{
        name: "rustic:ale_wort_bucket",
        texture: "ale_wort",
        texture_wine: "ale",
        output: "minecraft:bucket",
        level: 3,
        quality: false,
        brewed: "rustic:ale_bottle"
    },
    "rustic:bottle_of_apple_juice":{
        name: "rustic:bottle_of_apple_juice",
        texture: "apple_juice",
        texture_wine: "cider",
        output: "minecraft:glass_bottle",
        level: 1,
        quality: false,
        brewed: "rustic:cider_bottle"
    },
    "rustic:apple_juice_bucket":{
        name: "rustic:apple_juice_bucket",
        texture: "apple_juice",
        texture_wine: "cider",
        output: "minecraft:bucket",
        level: 3,
        quality: false,
        brewed: "rustic:cider_bottle"
    },
    "minecraft:honey_bottle":{
        name: "minecraft:honey_bottle",
        texture: "honey",
        texture_wine: "mead",
        output: "minecraft:glass_bottle",
        level: 1,
        quality: false,
        brewed: "rustic:mead_bottle"
    },
    "rustic:honey_bucket":{
        name: "rustic:honey_bucket",
        texture: "honey",
        texture_wine: "mead",
        output: "minecraft:bucket",
        level: 3,
        quality: false,
        brewed: "rustic:mead_bottle"
    }
}