import { ItemStack, system, world } from '@minecraft/server';
import '../../spawn_loot/spawn_loot';
import { appleTreeloot, oliveTreeloot, ironwoodTreeloot } from './leavesLootTable';
import { attemptToInventory } from '../functions';

export const allowedLogs = [
    'rustic:apple_log', 'rustic:apple_log_stripped',
    'rustic:ironwood_log', 'rustic:ironwood_log_stripped',
    'rustic:olive_log', 'rustic:olive_log_stripped'
];

export const leavesLoot = {
    "rustic:apple_leaves": {
        lootTable: appleTreeloot
    },
    "rustic:apple_leaves_grow": {
        lootTable: appleTreeloot
    },
    "rustic:ironwood_leaves": {
        lootTable: ironwoodTreeloot
    },
    "rustic:olive_leaves": {
        lootTable: oliveTreeloot
    },
    "rustic:olive_leaves_acacia": {
        lootTable: oliveTreeloot
    }
}

system.beforeEvents.startup.subscribe(eventData => {
    eventData.blockComponentRegistry.registerCustomComponent('rustic:on_random_tick', {
        onRandomTick(e) {
            const { block } = e;
            const { x, y, z } = block.location;

            const isDecaying = block.permutation.getState('rustic:decay');
            const isPlacedByPlayer = block.permutation.getState('rustic:placed');

            if(block.typeId == "rustic:apple_leaves_grow"){
                const appleStage = block.permutation.getState('r:grow_apple');
                const random = Math.random() * 100
                if ( random < 15 && appleStage != 3) {
                    if (block.below().typeId == block.typeId || block.below().typeId == "rustic:apple_leaves" || block.below().isAir){
                        block.setPermutation(block.permutation.withState("r:grow_apple", appleStage +1 ));
                    }
                }
            }

            if (isPlacedByPlayer) return;
            if (isDecaying) {
                const isLogNear = checkForLogsAroundLeaves(block);
                if (!isLogNear){
                    const elegibleLoot = leavesLoot[block.typeId].lootTable;

                    if(block.typeId == "rustic:apple_leaves_grow"){
                        const appleStage = block.permutation.getState('r:grow_apple');
                        if (appleStage == 3) block.dimension.spawnItem(new ItemStack("minecraft:apple"),block.center())
                    }

                    block.dimension.runCommand(`setblock ${x} ${y} ${z} air`);

                    block.dimension.spawnLoot(elegibleLoot,block.location)
                    checkAndDecayLeavesAround(block)
                }
                else block.setPermutation(block.permutation.withState('rustic:decay', false));
                
                return;
            }

        },
        beforeOnPlayerPlace: e => {
            const { player, block, face, permutationToPlace, dimension } = e;
            e.permutationToPlace = permutationToPlace.withState('rustic:placed', true);
        },
        onPlayerBreak: e => {
            const { player, block, dimension, brokenBlockPermutation } = e;
            if (brokenBlockPermutation.type.id == "rustic:apple_leaves_grow"){
                const appleStage = brokenBlockPermutation.getState('r:grow_apple');
                if (appleStage == 3) block.dimension.spawnItem(new ItemStack("minecraft:apple"),block.center())
            }

            const elegibleLoot = leavesLoot[brokenBlockPermutation.type.id].lootTable;
            block.dimension.spawnLoot(elegibleLoot,block.location)
        },
    });
});

system.beforeEvents.startup.subscribe(eventData => {
    eventData.blockComponentRegistry.registerCustomComponent('rustic:grow_before_generate', {
        onTick: e => {
            const { block, dimension } = e;
            const permutation = block.permutation.getState("rustic:placed");
            if (permutation) return;
            const random = Math.random() * 100
            if (random < 10) {
                block.setType("rustic:apple_leaves_grow")
            }

        },
    });
});

world.beforeEvents.playerInteractWithBlock.subscribe(eventData => {
    const block = eventData.block;
    if (!eventData.isFirstEvent || block.typeId != "rustic:apple_leaves_grow") return;
    const player = eventData.player;
    const equipment = player.getComponent('equippable');
    const selectedItem = equipment.getEquipment('Mainhand');
    const appleStage = block.permutation.getState('r:grow_apple');

    if(selectedItem != undefined && selectedItem.typeId == "minecraft:bone_meal" && appleStage != 3) {

        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 (selectedItem.amount > 1) {
                    selectedItem.amount -= 1;
                    equipment.setEquipment('Mainhand', selectedItem);
                } else if (selectedItem.amount === 1) {
                    equipment.setEquipment('Mainhand', undefined);
                }
            }
            if (block.below().isSolid) return;

            if (appleStage >= 3) return;

            block.setPermutation(block.permutation.withState("r:grow_apple", appleStage +1 ));
        })
        
        
    }
    else{
        if(appleStage != 3) return;
        system.run(() => {
            attemptToInventory(player,new ItemStack("minecraft:apple"), { x: block.center().x, y: block.center().y-1, z: block.center().z }, block.dimension);
            block.setPermutation(block.permutation.withState("r:grow_apple", 0 ));
        })
        

    }

});



world.afterEvents.playerBreakBlock.subscribe(eventData => {
    const brokenBlockPerm = eventData.brokenBlockPermutation;
    const block = eventData.block;

    // Verifica si el bloque eliminado es un tronco
    if (allowedLogs.includes(brokenBlockPerm.type.id)) {
        const doDecay = checkForLogsAround(block);

        if (!doDecay)checkAndDecayLeavesAround(block);
        
    }
});



export function checkAndDecayLeavesAround(block) {
    const adjacentBlocks = [
        block.north(),
        block.south(),
        block.east(),
        block.west(),
        block.above(),
        block.below()
    ];

    for (const adjacentBlock of adjacentBlocks) {
        if (adjacentBlock && adjacentBlock.hasTag("leaves")) {
            adjacentBlock.setPermutation(adjacentBlock.permutation.withState('rustic:decay', true));
        }
    }
}

export function checkForLogsAround(block) {
    const adjacentBlocks = [
        block.north(),
        block.south(),
        block.east(),
        block.west(),
        block.above(),
        block.below()
    ];

    let isLogNear = false

    for (const adjacentBlock of adjacentBlocks) {
        if (adjacentBlock && adjacentBlock.hasTag("log")) {
            isLogNear = true
        }
    }

    return isLogNear;
}

export function checkForLogsAroundLeaves(block) {
    const adjacentBlocks = [
        block.north(),
        block.north()?.east(),
        block.north()?.west(),
        block.south(),
        block.south()?.east(),
        block.south()?.west(),
        block.east(),
        block.west(),
        block.above(),
        block.below(),
        block.north(2),
        block.north(2)?.east(),
        block.north(2)?.west(),
        block.south(2),
        block.south(2)?.east(),
        block.south(2)?.west(),
        block.east(2),
        block.east(2)?.north(),
        block.east(2)?.south(),
        block.west(2),
        block.west(2)?.north(),
        block.west(2)?.south(),
    ];

    let isLogNear = false

    for (const adjacentBlock of adjacentBlocks) {
        if (adjacentBlock && adjacentBlock.hasTag("log")) {
            isLogNear = true
        }
    }

    return isLogNear;
}


