import * as mc from "@minecraft/server";

export const up = { x: 0, y: 1, z: 0 };
export const down = { x: 0, y: -1, z: 0 };
export const left = { x: -1, y: 0, z: 0 };
export const right = { x: 1, y: 0, z: 0 };
export const forward = { x: 0, y: 0, z: 1 };
export const back = { x: 0, y: 0, z: -1 };

export function add(v1, v2) {
  return { x: v1.x + v2.x, y: v1.y + v2.y, z: v1.z + v2.z };
}
export function subtract(v1, v2) {
  return { x: v1.x - v2.x, y: v1.y - v2.y, z: v1.z - v2.z };
}
export function multiply(v, sca) {
  return { x: v.x * sca, y: v.y * sca, z: v.z * sca };
}
export function magnitude(v) {
  return Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}
export function normalize(v) {
  const m = magnitude(v);
  return { x: v.x / m, y: v.y / m, z: v.z / m };
}
export function random(n) {
  return {
    x: (Math.random() - 0.5) * n,
    y: (Math.random() - 0.5) * n,
    z: (Math.random() - 0.5) * n,
  };
}
export function cross(v1, v2) {
  return {
    x: v1.y * v2.z - v1.z * v2.y,
    y: v1.z * v2.x - v1.x * v2.z,
    z: v1.x * v2.y - v1.y * v2.x,
  };
}
export function flatten(vector, axis, norm = true) {
  let value;
  if (axis === "x") value = { x: 0, y: vector.y, z: vector.z };
  if (axis === "y") value = { x: vector.x, y: 0, z: vector.z };
  if (axis === "z") value = { x: vector.x, y: vector.y, z: 0 };
  return norm ? normalize(value) : value;
}
export function sqr(num) {
  return num * num;
}
export function distance(v1, v2) {
  return Math.sqrt(sqr(v1.x - v2.x) + sqr(v1.y - v2.y) + sqr(v1.z - v2.z));
}
export function string(v) {
  return `${Math.round(v.x*10)/10} ${Math.round(v.y*10)/10} ${Math.round(v.z*10)/10}`;
}
export function getCenterFromXYZ(x, y, z) {
  return Math.sqrt((x / 2) ** 2 + (y / 2) ** 2 + (z / 2) ** 2) + 1;
}
export function getBlockLocalCoord(block, coords) {
  const blockRotation = block.permutation.getState("facing_direction");
  let localX = 0;
  let localY = 0;
  let localZ = 0;

  switch (blockRotation) {
      case 0: // Down
          localX = coords.x;
          localY = -coords.y; 
          localZ = coords.z;
          break;
      case 1: // Up
          localX = coords.x;
          localY = coords.y; 
          localZ = coords.z;
          break;
      case 2: // North
          localX = -coords.x;
          localY = coords.y;
          localZ = -coords.z; 
          break;
      case 3: // South
          localX = coords.x;
          localY = coords.y;
          localZ = coords.z;
          break;
      case 4: // West
          localX = -coords.z;
          localY = coords.y;
          localZ = coords.x;
          break;
      case 5: // East
          localX = coords.z;
          localY = coords.y;
          localZ = -coords.x;
          break;
  }
  return { 
      x: localX + block.location.x, 
      y: localY + block.location.y, 
      z: localZ + block.location.z 
  };
}