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

system.beforeEvents.startup.subscribe((initEvent) => {
    initEvent.blockComponentRegistry.registerCustomComponent("rustic:grape_growing", {
        onRandomTick: e => {
            const { block, dimension } = e;

            const currentState = block.permutation.getState("r:stages");
            
            if(block.hasTag("MaxStage")) return;

            if ( (Math.random() * 100) > 33 ) return;

            block.setPermutation(block.permutation.withState("r:stages", currentState + 1));
            
            if (currentState == 3){
                if (block.above().typeId == 'rustic:rope'){
                    if(!block.above().hasTag("grape")){
                        const ropePosition = block.above().permutation.getState("minecraft:block_face");

                        if(ropePosition == 'up' || ropePosition == 'down') return;

                        block.above().setPermutation(block.above().permutation.withState("r:grape", 1));
                    };
                }
            }
            if (currentState == 4){
                if (block.above()?.typeId == 'rustic:rope' && block.above().north()?.typeId == 'rustic:rope'){
                    if(!block.above().north().hasTag("grape")){
                        const ropePosition = block.above().north().permutation.getState("minecraft:block_face");

                        if(ropePosition == 'up' || ropePosition == 'down') return;

                        block.above().north().setPermutation(block.above().north().permutation.withState("r:grape", 2));
                    };
                    

                }
            }
            if (currentState == 5){
                if (block.above().typeId == 'rustic:rope' && block.above().west().typeId == 'rustic:rope'){
                    if(!block.above().west().hasTag("grape")){
                        const ropePosition = block.above().west().permutation.getState("minecraft:block_face");

                        if(ropePosition == 'up' || ropePosition == 'down') return;

                        block.above().west().setPermutation(block.above().west().permutation.withState("r:grape", 4));
                    };
                    

                }
            }
            if (currentState == 6){
                if (block.above().typeId == 'rustic:rope' && block.above().south().typeId == 'rustic:rope'){
                    if(!block.above().south().hasTag("grape")){
                        const ropePosition = block.above().south().permutation.getState("minecraft:block_face");

                        if(ropePosition == 'up' || ropePosition == 'down') return;

                        block.above().south().setPermutation(block.above().south().permutation.withState("r:grape", 3));
                    };
                    

                }
            }
            if (currentState == 7){
                if (block.above().typeId == 'rustic:rope' && block.above().east().typeId == 'rustic:rope'){
                    if(!block.above().east().hasTag("grape")){
                        const ropePosition = block.above().east().permutation.getState("minecraft:block_face");

                        if(ropePosition == 'up' || ropePosition == 'down') return;

                        block.above().east().setPermutation(block.above().east().permutation.withState("r:grape", 5));
                    };
                }
                block.setPermutation(block.permutation.withState("r:stages", 3));
            }
            
        },
        onPlayerInteract: e => {
            const { player, block, dimension, face, faceLocation } = e;
            const item = player.getComponent('inventory').container.getItem(player.selectedSlotIndex);

            if (item == undefined) return;

            if (item.typeId == 'minecraft:bone_meal'){

                if (block.hasTag("MaxStage")) return;

                block.dimension.spawnParticle("minecraft:crop_growth_emitter", block.center());
                block.dimension.playSound("item.bone_meal.use", block.center());
                const equipment = player.getComponent('equippable');
                if (player.getGameMode() !== "creative") {
                    if (item.amount > 1) {
                        item.amount -= 1;
                        equipment.setEquipment('Mainhand', item);
                    } else if (item.amount === 1) {
                        equipment.setEquipment('Mainhand', undefined);
                    }
                }
                
                if ( (Math.random() * 100) > 50 ) return;

                const growState = block.permutation.getState("r:stages");
                block.setPermutation(block.permutation.withState("r:stages", growState + 1));

                const currentState = block.permutation.getState("r:stages");

                if (currentState == 3){
                    if (block.above().typeId == 'rustic:rope'){
                        if(!block.above().hasTag("grape")){
                            const ropePosition = block.above().permutation.getState("minecraft:block_face");
    
                            if(ropePosition == 'up' || ropePosition == 'down') return;
    
                            block.above().setPermutation(block.above().permutation.withState("r:grape", 1));
                        };
                    }
                }
                if (currentState == 4){
                    if (block.above().typeId == 'rustic:rope' && block.above().north().typeId == 'rustic:rope'){
                        if(!block.above().north().hasTag("grape")){
                            const ropePosition = block.above().north().permutation.getState("minecraft:block_face");
    
                            if(ropePosition == 'up' || ropePosition == 'down') return;
    
                            block.above().north().setPermutation(block.above().north().permutation.withState("r:grape", 2));
                        };
                        
    
                    }
                }
                if (currentState == 5){
                    if (block.above().typeId == 'rustic:rope' && block.above().west().typeId == 'rustic:rope'){
                        if(!block.above().west().hasTag("grape")){
                            const ropePosition = block.above().west().permutation.getState("minecraft:block_face");
    
                            if(ropePosition == 'up' || ropePosition == 'down') return;
    
                            block.above().west().setPermutation(block.above().west().permutation.withState("r:grape", 4));
                        };
                        
    
                    }
                }
                if (currentState == 6){
                    if (block.above().typeId == 'rustic:rope' && block.above().south().typeId == 'rustic:rope'){
                        if(!block.above().south().hasTag("grape")){
                            const ropePosition = block.above().south().permutation.getState("minecraft:block_face");
    
                            if(ropePosition == 'up' || ropePosition == 'down') return;
    
                            block.above().south().setPermutation(block.above().south().permutation.withState("r:grape", 3));
                        };
                        
    
                    }
                }
                if (currentState == 7){
                    if (block.above().typeId == 'rustic:rope' && block.above().east().typeId == 'rustic:rope'){
                        if(!block.above().east().hasTag("grape")){
                            const ropePosition = block.above().east().permutation.getState("minecraft:block_face");
    
                            if(ropePosition == 'up' || ropePosition == 'down') return;
    
                            block.above().east().setPermutation(block.above().east().permutation.withState("r:grape", 5));
                        };
                    }
                    block.setPermutation(block.permutation.withState("r:stages", 3));
                }
                
            }
        },
    });
    initEvent.blockComponentRegistry.registerCustomComponent("rustic:grape_fruit", {
        onRandomTick: e => {
            const { block, dimension } = e;

            if(!block.hasTag("grape")) return;

            const leafType = block.permutation.getState("r:grape");

            if(leafType == 1) return;

            const currentState = block.permutation.getState("r:fruit");
            
            if(currentState == true) return;

            if ( (Math.random() * 100) > 33 ) return;

            block.setPermutation(block.permutation.withState("r:fruit", true));
            
            
        },
    });
});

world.beforeEvents.playerInteractWithBlock.subscribe(eventData => {
    const block = eventData.block;
    const player = eventData.player;

    if (!block.hasTag("grape"))return;
    
    if(!block.hasTag("fruit"))return;

    const fruit = new ItemStack("rustic:grapes", 1)
    const poisonFruit = new ItemStack("rustic:poisonous_grapes", 1)
    system.run( () => {
        player.dimension.spawnItem(fruit,block.center())

        if ( (Math.random() * 100) < 50 ) {
            player.dimension.spawnItem(fruit,block.center())
        }
        if ( (Math.random() * 100) < 5 ) {
            player.dimension.spawnItem(poisonFruit,block.center())
        }

        block.setPermutation(block.permutation.withState("r:fruit", false));
        
    })

    eventData.cancel = true
});

world.beforeEvents.playerInteractWithBlock.subscribe(eventData => {
    const block = eventData.block;
    const player = eventData.player;
    const item = eventData.itemStack;

    if (item == undefined) return;

    if (!block.hasTag("grape"))return;
    
    if(block.hasTag("fruit") || block.hasTag("midLeaf"))return;

    if (item.typeId != 'minecraft:bone_meal') return;

    const equipment = player.getComponent('equippable');

    system.run( () => {
        block.dimension.spawnParticle("minecraft:crop_growth_emitter", block.center());
        block.dimension.playSound("item.bone_meal.use", block.center());
        if (player.getGameMode() !== "creative") {
            if (item.amount > 1) {
                item.amount -= 1;
                equipment.setEquipment('Mainhand', item);
            } else if (item.amount === 1) {
                equipment.setEquipment('Mainhand', undefined);
            }
        }
    })

    

    if ( (Math.random() * 100) > 40 ) return;
    
    system.run( () => {
        block.setPermutation(block.permutation.withState("r:fruit", true));
    })

    eventData.cancel = true
});

world.beforeEvents.playerBreakBlock.subscribe(eventData => {
    const block = eventData.block;
    const player = eventData.player;

    if (player.getGameMode() == "creative")return;

    if (!block.hasTag("grape"))return;
    
    if(!block.hasTag("fruit"))return;

    const fruit = new ItemStack("rustic:grapes", 1)
    system.run( () => {
        eventData.dimension.spawnItem(fruit,block.center())
    })
})