import {
  world,
  ItemStack
} from "@minecraft/server";
world.beforeEvents.worldInitialize.subscribe(initEvent => {
  initEvent.blockComponentRegistry.registerCustomComponent('we:sand_layer_place', {
    onPlace(e) {
      const {
        block
      } = e;
      const permutation = block.permutation;
      if (permutation.getState('we:layer_level') === 0) {
        const randomRotation = Math.floor(Math.random() * 4);
        const newPermutation = permutation.withState('we:random_rotation', randomRotation);
        block.setPermutation(newPermutation);
      }
    }
  });
  initEvent.blockComponentRegistry.registerCustomComponent('we:sand_layer_destroy', {
    onPlayerDestroy(e) {
      const {
        player,
        dimension,
        block
      } = e;
      const {
        destroyedBlockPermutation: perm
      } = e;
      if (!player || !player.getComponent('equippable')) return;
      const selectedItem = player.getComponent('equippable').getEquipment('Mainhand');
      if (!selectedItem || !selectedItem.hasTag('minecraft:is_shovel')) {
        return;
      }
      const layerLevel = 1+perm.getState('we:layer_level');
      const sandItem = new ItemStack(block.typeId, layerLevel);
      dimension.spawnItem(sandItem, {x:block.center().x,y:block.y+1,z:block.center().z});
    }
  });
  initEvent.blockComponentRegistry.registerCustomComponent('we:sand_layer_interact', {
    onPlayerInteract(e) {
      const {
        block,
        player
      } = e;
      const equipment = player.getComponent('equippable');
      const selectedItem = equipment.getEquipment('Mainhand');
      if (selectedItem && selectedItem.typeId === block.typeId) {
        
        const permutation = block.permutation;
        const currentLayerLevel = permutation.getState('we:layer_level');
        if (currentLayerLevel <= 6) {
          e.cancel = true;
          
          const newLayerLevel = currentLayerLevel + 1;
          const newPermutation = permutation.withState('we:layer_level', newLayerLevel);
          block.setPermutation(newPermutation);
          e.dimension.playSound('dig.sand', block)
          if (!e.player.matches({gameMode: 'creative'})) {
            if (selectedItem.amount > 1) {
              selectedItem.amount -= 1;
              equipment.setEquipment('Mainhand', selectedItem);
            } else {
              equipment.setEquipment('Mainhand', undefined);
            }
          }
        }
      }
    }
  });
});