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

function getOppositeDirection(direction) {
  switch (direction) {
    case Direction.North: return Direction.South;
    case Direction.South: return Direction.North;
    case Direction.East: return Direction.West;
    case Direction.West: return Direction.East;
  }
}

function directionToVector3(direction) {
  switch (direction) {
    case Direction.North: return { x: 0, y: 0, z: -1 };
    case Direction.South: return { x: 0, y: 0, z: 1 };
    case Direction.West: return { x: -1, y: 0, z: 0 };
    case Direction.East: return { x: 1, y: 0, z: 0 };
  }
}

world.beforeEvents.worldInitialize.subscribe(initEvent => {
  initEvent.blockComponentRegistry.registerCustomComponent('pa:valla', {
    onPlayerDestroy: e => {
      for (const direction of [Direction.North, Direction.South, Direction.East, Direction.West]) {
        const oppositeDirection = getOppositeDirection(direction);
        const blockToCheck = e.block.offset(directionToVector3(oppositeDirection));
        for (const childDirection of [Direction.North, Direction.South, Direction.East, Direction.West]) {
          const childOpposite = getOppositeDirection(childDirection);
          const childBlock = blockToCheck.offset(directionToVector3(childOpposite));
          try {
            blockToCheck.setPermutation(blockToCheck.permutation.withState(`pa:${childOpposite.toLowerCase()}`, !childBlock.typeId.includes("minecraft:air")));
          } catch (error) {}
        }
      }
    },
    beforeOnPlayerPlace: e => {
      e.permutationToPlace = e.permutationToPlace.withState("pa:in_world", true);
      for (const direction of [Direction.North, Direction.South, Direction.East, Direction.West]) {
        const oppositeDirection = getOppositeDirection(direction);
        const blockToCheck = e.block.offset(directionToVector3(oppositeDirection));
        if (blockToCheck.typeId.includes("minecraft:air")) continue;
        e.permutationToPlace = e.permutationToPlace.withState(`pa:${oppositeDirection.toLowerCase()}`, !blockToCheck.typeId.includes("minecraft:air"));
        try {
          blockToCheck.setPermutation(blockToCheck.permutation.withState(`pa:${direction.toLowerCase()}`, true));
        } catch (error) {}
      }
    }
  });
});
