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

export const flowers = {
    "rustic:aloe_vera": {
        permutation: 1
    },
    "rustic:blood_orchid": {
        permutation: 2
    },
    "rustic:chamomile": {
        permutation: 3
    },
    "rustic:cohosh": {
        permutation: 4
    },
    "rustic:core_root": {
        permutation: 5
    },
    "rustic:deathstalk_mushroom": {
        permutation: 6
    },
    "rustic:ginseng": {
        permutation: 7
    },
    "rustic:horsetail": {
        permutation: 8
    },
    "rustic:marsh_mallow": {
        permutation: 9
    },
    "rustic:mooncap_mushroom": {
        permutation: 10
    },
    "rustic:wind_thistle": {
        permutation: 11
    },
    "rustic:wildberry_bush": {
        permutation: 12
    },
    "rustic:vanta_lily": {
        permutation: 13
    }
}

world.afterEvents.itemStartUseOn.subscribe(eventData => {
    const player = eventData.source;
    const block = eventData.block;
    const item = player.getComponent('inventory').container.getItem(player.selectedSlotIndex);
    
    if (block.typeId != "minecraft:flower_pot") return;

    if (!flowers[eventData.itemStack.typeId]) return;

    const flower = flowers[eventData.itemStack.typeId];
    const equipment = player.getComponent('equippable');

    system.run( () => {
        if (player.getGameMode() !== "creative") {
            if (item.amount > 1) {
                item.amount -= 1;
                equipment.setEquipment('Mainhand', item);
            } else if (item.amount === 1) {
                equipment.setEquipment('Mainhand', undefined);
            }
        }
        block.setPermutation(BlockPermutation.resolve("rustic:flower_pot", {"r:variants": flower.permutation}));
    })
});

world.afterEvents.playerBreakBlock.subscribe(eventData => {
    if (eventData.brokenBlockPermutation.type.id === "rustic:flower_pot") dropItems(eventData);

});

world.afterEvents.blockExplode.subscribe(eventData => {
    if (eventData.explodedBlockPermutation.type.id === "rustic:flower_pot") dropItems(eventData);
});


export function dropItems(data){

    const variant = data.brokenBlockPermutation.getState("r:variants")

    if ( variant === 0 ) return;

    const flowerData = Object.entries(flowers).find(([key, value]) => value.permutation === variant);

    if (!flowerData) return;

    const [key, value] = flowerData;

    data.dimension.spawnItem(new ItemStack(key), data.block.center());
}
