import {
  world,
  ItemStack
} from "@minecraft/server";
world.beforeEvents.worldInitialize.subscribe(initEvent => {
  initEvent.blockComponentRegistry.registerCustomComponent('we:slab_interact', {
    onPlayerInteract(e) {
      const {
        block,
        player,
        face
      } = e;
      const equipment = player.getComponent('equippable');
      const selectedItem = equipment.getEquipment('Mainhand');
      if (selectedItem?.typeId === block.typeId && !block.permutation.getState('we:state')) {
        const verticalHalf = block.permutation.getState('minecraft:vertical_half');
        const isBottomUp = verticalHalf === 'bottom' && face === 'Up';
        const isTopDown = verticalHalf === 'top' && face === 'Down';
        if (isBottomUp || isTopDown) {
          if (!e.player.matches({
              gameMode: 'creative'
            })) {
            if (selectedItem.amount > 1) {
              selectedItem.amount -= 1;
              equipment.setEquipment('Mainhand', selectedItem);
            } else if (selectedItem.amount === 1) {
              equipment.setEquipment('Mainhand', undefined);
            }
          }
          block.setPermutation(block.permutation.withState('we:state', true));
          if (block.hasTag('sound_basalt')) {
            player.playSound('use.basalt');
          } else if (block.hasTag('sound_calcite')) {
            player.playSound('place.calcite');
          } else if (block.hasTag('sound_dripstone')) {
            player.playSound('place.dripstone_block');
          } else if (block.hasTag('sound_metal')) {
            player.playSound('use.stone');
          } else if (block.hasTag('sound_wood')) {
            player.playSound('dig.wood');
          } else if (block.hasTag('sound_cherry_wood')) {
            player.playSound('place.cherry_wood');
          } else if (block.hasTag('sound_nether_wood')) {
            player.playSound('place.nether_wood');
          } else if (block.hasTag('sound_mud_bricks')) {
            player.playSound('block.mud_bricks.place');
          } else if (block.hasTag('sound_nether_stem')) {
            player.playSound('dig.stem');
          } else {
            player.playSound('use.stone');
          }
        }
      }
    }
  });
  initEvent.blockComponentRegistry.registerCustomComponent('we:slab_destroy', {
    onPlayerDestroy(e) {
      const {
        player,
        dimension
      } = e;
      const {
        destroyedBlockPermutation: perm
      } = e;
      if (!player) {
        return;
      }
      if (e.player.matches({
          gameMode: 'creative'
        })) return;
      const slabItem = perm.getItemStack(1);
      if (slabItem) {
        dimension.spawnItem(slabItem, e.block.location);
      }
    }
  });
});