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


      if (above !== 'we:salt_crystal_block') {
        const newPermutation = permutation.withState('we:height', 0);
        block.setPermutation(newPermutation);
        return;
      } else if (above === 'we:salt_crystal_block' && below !== 'we:salt_crystal_block') {
        const newPermutation = permutation.withState('we:height', 2);
        block.setPermutation(newPermutation);
        return;
      } else if (above === 'we:salt_crystal_block' && below === 'we:salt_crystal_block') {
        const newPermutation = permutation.withState('we:height', 1);
        block.setPermutation(newPermutation);
        return;
      }
    }
  });

initEvent.blockComponentRegistry.registerCustomComponent('we:salt_crystal_growth', {
    onRandomTick(e) {
      const {
        block
      } = e;

      const below = block.below().typeId;
      const rand = Math.floor(Math.random()*10); 

      if (block.typeId !== 'we:salt_crystal_block' || below !== 'we:salt_block' || rand > 0) return;

      if(block.above().isAir) {
       e.dimension.playSound('break.pointed_dripstone', block.above().location, {pitch: 1.2, volume: 0.333})
       block.above().setType('we:salt_crystal_block');
       return;
      } else if (block.above().typeId === block.typeId && block.above(2).isAir) {
       e.dimension.playSound('break.pointed_dripstone', block.above(2).location, {pitch: 1.2, volume: 0.333})
       block.above(2).setType('we:salt_crystal_block');
       return;
      }

      
    }
  });
});