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

system.beforeEvents.startup.subscribe(eventData => {
    eventData.blockComponentRegistry.registerCustomComponent("rustic:apiary", {
        beforeOnPlayerPlace: e => {
            const { player, block, face, permutationToPlace, dimension } = e;
            const blockLocation = block.center()
            system.run(() => {
                const brewingEntity = block.dimension.spawnEntity("rustic:apiary_ui", {x: blockLocation.x, y: block.location.y, z: blockLocation.z})
	            brewingEntity.nameTag = `apiary`
            })
            



        },
        onRandomTick: e => {
            const block = e.block;
            const dimension = e.dimension;

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

                //Verificar el primer slot
                let beeSlot = apiaryContainer.getItem(0);
                let honeycombSlot = apiaryContainer.getItem(1);
                if(!beeSlot) {return;}

                if (beeSlot.typeId == "rustic:bee"){
                    let beeCount = beeSlot.amount;

                    let baseProbability = 0.2;
                    let additionalProbability = 0.015 * (beeCount - 1);
                    let finalProbability = Math.min(baseProbability + additionalProbability, 1);

                    if (Math.random() < finalProbability) {
                        if (!honeycombSlot || honeycombSlot.typeId == "minecraft:honeycomb") {
                            let honeycombCount = honeycombSlot ? honeycombSlot.amount : 0

                            if (honeycombCount < 64){
                                const newHoneycomb = new ItemStack("minecraft:honeycomb", honeycombSlot ? honeycombSlot.amount + 1 : 1);
                                apiaryContainer.setItem(1, newHoneycomb);
                            }
                            
                        }
                        
                    }

                    if (beeCount > 1 && beeCount < 64){
                        if (Math.random() < finalProbability) {
                            const newBee = new ItemStack("rustic:bee", beeCount + 1);
                            apiaryContainer.setItem(0,newBee)
                        }
                        
                    }


                }
                
            }
        },
    });
});

//ticking 6,6