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

world.beforeEvents.worldInitialize.subscribe(initEvent => {

initEvent.blockComponentRegistry.registerCustomComponent('we:trapdoor_interact', {
    onPlayerInteract(e) {

      const {
        block
      } = e;

      const currentState = block.permutation.getState('we:open_bit');

      const newOpenState = !currentState;

      const newPermutation = BlockPermutation.resolve(block.typeId, {
        ...block.permutation.getAllStates(),
        'we:open_bit': newOpenState
      });

      block.setPermutation(newPermutation);

      const sound = currentState ? 'open.cherry_wood_trapdoor' : 'close.cherry_wood_trapdoor';

      e.dimension.playSound(sound, block.center());

    }
  });
});