import { system, world } from "@minecraft/server";

const unmovableBlocksId = [
  "tvf_randev:orbital_canon",
  "tvf_randev:high_pressure_generator",
];

const directionMethods_expand = {
  0: (loc) => ({ x: loc.x, y: loc.y - 1, z: loc.z }),
  1: (loc) => ({ x: loc.x, y: loc.y + 1, z: loc.z }),
  2: (loc) => ({ x: loc.x, y: loc.y, z: loc.z + 1 }),
  3: (loc) => ({ x: loc.x, y: loc.y, z: loc.z - 1 }),
  4: (loc) => ({ x: loc.x + 1, y: loc.y, z: loc.z }),
  5: (loc) => ({ x: loc.x - 1, y: loc.y, z: loc.z }),
};
const directionMethods_retracted = {
  0: (loc) => ({ x: loc.x, y: loc.y + 1, z: loc.z }),
  1: (loc) => ({ x: loc.x, y: loc.y - 1, z: loc.z }),
  2: (loc) => ({ x: loc.x, y: loc.y, z: loc.z - 1 }),
  3: (loc) => ({ x: loc.x, y: loc.y, z: loc.z + 1 }),
  4: (loc) => ({ x: loc.x - 1, y: loc.y, z: loc.z }),
  5: (loc) => ({ x: loc.x + 1, y: loc.y, z: loc.z }),
};

world.afterEvents.pistonActivate.subscribe((event) => {
  const dimension = event.dimension;
  const pistnoBlock = event.piston.block;
  const dir = pistnoBlock.permutation.getState("facing_direction");
  const state = event.piston.state;

  const attachedLocs = event.piston.getAttachedBlocksLocations();

  let blocksLocsToRemove = [];

  system.runTimeout(() => {
    for (const aLoc of attachedLocs) {
      const nextLoc =
        state == "Expanded" || state == "Expanding"
          ? directionMethods_expand[dir](aLoc)
          : directionMethods_retracted[dir](aLoc);
      const attachedBlock = dimension.getBlock(nextLoc);

      if (!attachedBlock) continue;

      if (unmovableBlocksId.includes(attachedBlock.typeId)) {
        blocksLocsToRemove.push(nextLoc);
      }
    }

    if (blocksLocsToRemove.length === 0) return;

    for (const loc of blocksLocsToRemove) {
      try {
        dimension.runCommand(`setblock ${loc.x} ${loc.y} ${loc.z} air destroy`);
      } catch {}
    }
  }, 5);
});
