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

world.beforeEvents.playerInteractWithBlock.subscribe(eventData => {
    const { itemStack: item, player: player, block, blockFace: face } = eventData;
    if (!eventData.isFirstEvent) return;
    const equipment = player.getComponent('equippable');
    const pattern = /^rustic:.*_slab$/;


    if (!pattern.test(item?.typeId) || block.typeId != item?.typeId) return;

    if (block.permutation.getState('rustic:double') ? true : false) return;

    const verticalHalf = block.permutation.getState('minecraft:vertical_half');

    if (face == 'Up' && verticalHalf == 'bottom' || face == 'Down' && verticalHalf == 'top') {
        system.run( () => {block.setPermutation(block.permutation.withState("rustic:double",true));})
    }
    else return;
    const soundId = block.hasTag("wood") ? "step.wood" : "step.stone";
    system.run( () => {
        block.dimension.playSound(soundId,block.center(),{
            pitch: 1,
            volume: 10.0,
        })
        if (player.getGameMode() !== "Creative") {
            if (item.amount > 1) {
                item.amount -= 1;
                equipment.setEquipment('Mainhand', item);
            } else if (item.amount === 1) {
                equipment.setEquipment('Mainhand', undefined);
            }
        }
    })

    eventData.cancel = true

});