import {
  world,
  system
} from "@minecraft/server";
world.beforeEvents.worldInitialize.subscribe(initEvent => {
  initEvent.blockComponentRegistry.registerCustomComponent('we:double_plant', {
    onTick(e) {
      const {
        block
      } = e;
      if (block.typeId === 'we:air') return;
      const above = block.above().typeId;
      const below = block.below().typeId;

      if (above !== block.typeId && below !== block.typeId) {

        const {
          x,
          y,
          z
        } = block.center();

        e.dimension.runCommandAsync(`setblock ${x} ${y} ${z} air destroy`);

      }
    },
    beforeOnPlayerPlace(e) {
      const {
        block
      } = e;
      const above = block.above();

      if(above.isAir) {
        system.runTimeout(() => {
          above.setType(block.typeId);
          const permutation = above.permutation;

          const newPermutation = permutation.withState('we:upper_block_bit', true);
          above.setPermutation(newPermutation);
        }, 1);
      } else {
        e.cancel = true;
      }

    }

  });
});