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

system.beforeEvents.startup.subscribe(eventData => {
    eventData.blockComponentRegistry.registerCustomComponent('rustic:bone_meal', {
        onPlayerInteract(e) {
            const { block, player, dimension } = e;

            const equipment = player.getComponent('equippable');
            const selectedItem = equipment.getEquipment('Mainhand');

            if (selectedItem && (selectedItem.typeId === 'minecraft:bone_meal')) {

                block.dimension.spawnParticle('minecraft:crop_growth_emitter', block.center());
                block.dimension.playSound("item.bone_meal.use", block.center());

                if (player.matches({ gameMode: GameMode.survival })) {
                    if (selectedItem.amount > 1) {
                        selectedItem.amount -= 1;
                        equipment.setEquipment('Mainhand', selectedItem);
                    } else {
                        equipment.setEquipment('Mainhand', undefined);
                    }
                }

                const growChance = Math.random()

                if(growChance > 0.6 && growChance < 0.85 || player.matches({ gameMode: GameMode.creative })) {
                    const treeSize = Math.random();
                    let treeType = trees[block.typeId].small
                    if ( treeSize < 0.25 ) treeType = trees[block.typeId].medium
                    dimension.placeFeature(treeType,block.center())
                }
            }
        },
        onRandomTick: e => {
            const { block, dimension } = e;
            for (let y = 1; y <= 5; y++){
                if(block.above(y).isSolid || block.above(y).hasTag("rustic:isSolid")){
                    return
                }
            }

            const growChance = Math.random();

            if(growChance > 0.6 && growChance < 0.85) {
                
                const treeSize = Math.random();
                let treeType = trees[block.typeId].small
                if ( treeSize < 0.25 ) treeType = trees[block.typeId].medium
                dimension.placeFeature(treeType,block.center())
            }
        },
    });
});

export const trees = {
    "rustic:apple_sapling": {
        small: "rustic:small_apple_tree_feature",
        medium: "rustic:small_apple_tree_feature"
    },
    "rustic:ironwood_sapling": {
        small: "rustic:small_ironwood_tree_feature",
        medium: "rustic:medium_ironwood_tree_feature"
    },
    "rustic:olive_sapling": {
        small: "rustic:small_olive_tree_feature",
        medium: "rustic:small_olive_tree_feature"
    }
}