import { system, world, BlockPermutation } from '@minecraft/server';
import { decrementStack, getOppositeDirection, DirectionType, cardinalSides } from './utils/helper';
import { directionToVector3 } from './utils/math';

world.beforeEvents.worldInitialize.subscribe(initEvent => {
  initEvent.blockComponentRegistry.registerCustomComponent('pa:losa', {
    beforeOnPlayerPlace: e => {
      let playerEquipment = e.player.getComponent('equippable')?.getEquipment('Mainhand');
      if (!playerEquipment) return;

      let face = getOppositeDirection(e.face);
      let blockToCheck = e.block.offset(directionToVector3(face));
      const blockStateDouble = 'pa:is_double';
      const blockStateHalf = 'minecraft:vertical_half';

      if (blockToCheck.permutation.getState(blockStateDouble)) return;
      if (blockToCheck.typeId !== playerEquipment.typeId) return;

      if (face === 'Up' || face === 'Down') {
        const state = blockToCheck.permutation.getState(blockStateHalf);
        if ((face === 'Up' && state === 'top') || (face === 'Down' && state === 'bottom')) {
          blockToCheck.dimension.playSound("use.stone", blockToCheck.location, { pitch: 0.8, volume: 1.0 });

          blockToCheck.setPermutation(BlockPermutation.resolve(blockToCheck.typeId, {
            [blockStateDouble]: true
          }));

          e.cancel = true;
          decrementStack(e.player);
        }
      }
    },
  });
});
