const magnetizeValue = (value: number, size: number) => {
  // 0–n range
  const index = value / size;
  // magnetize index (i.e. ease in towards nearest integer)
  const magnetizedIndex = index + Math.sin(2 * PI * index - PI) / (2 * PI);
  // convert back to pixel
  return magnetizedIndex * size;
};

const getRotation = (id: string | undefined) => {
  if (id === undefined) return 0;
  const transform = $("#" + id).css("transform");
  if (transform == "none" || !transform) return 0;
  const values = transform.split("(")[1].split(")")[0].split(",");
  const a = parseFloat(values[0]);
  const b = parseFloat(values[1]);
  const angle = Math.round(Math.atan2(b, a) * RAD_TO_DEG);
  return ((angle % 360) + 360) % 360;
};

const getProjection = (x: number, y: number, rotation: number) => {
  const a = rotation * DEG_TO_RAD;
  return x * Math.cos(a) + y * Math.sin(a);
};

const getAngle = (
  vector1: { x: number; y: number },
  vector2: { x: number; y: number },
  startRotation: number,
  snap: boolean = false,
) => {
  const cross = vector1.x * vector2.y - vector1.y * vector2.x;
  const dot = vector1.x * vector2.x + vector1.y * vector2.y;
  const angleDelta = Math.atan2(cross, dot) * RAD_TO_DEG;
  const newRotation = (((startRotation + angleDelta) % 360) + 360) % 360;
  if (snap && (newRotation % 45 < 3 || newRotation % 45 > 42)) {
    return Math.round(newRotation / 45) * 45;
  }
  return newRotation;
};

const rotateTransform = (deg: number, tx = 0, ty = 0) => {
  let t = `translate(-50%, -50%) rotate(${deg}deg)`;
  if (tx !== 0) t += ` translateX(${tx}px)`;
  if (ty !== 0) t += ` translateY(${ty}px)`;
  return t;
};

const chairCount = (size: number) => Math.round((size - boxSize) / (2 * boxSize));

const ellipseCircumference = (a: number, b: number) => {
  return Math.PI * (3 * (a + b) - Math.sqrt((3 * a + b) * (3 * b + a)));
};

const getOtherRadius = (circumference: number, b: number) => {
  const x = 3 * b - circumference / Math.PI;
  return abcFormula(6, 6 * x - 10 * b, x * x - 3 * b * b);
};
/*
o/pi = 3(a + b) - sqrt((3a + b)(3b + a))

(3a + b) (3b + a) = (3(a + b) - o/pi) ^2

(3a + b) (3b + a) = (3a + (3b - o/pi)) ^2

(3a + b) (3b + a) = (3a + (3b-o/pi)) (3a + (3b-o/pi))

10ab + 3a^2 + 3bb = 9a^2 + 6a(3b-o/pi) + (3b-o/pi)(3b-o/pi)

0 = 6a^2 + (6(3b-o/pi) - 10b)* a + (3b-o/pi)(3b-o/pi) - 3bb
*/
const abcFormula = (a: number, b: number, c: number) => {
  return (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
};

const rotateXY = (x: number, y: number, rad: number) => {
  const rotatedX = x * Math.cos(rad) - y * Math.sin(rad);
  const rotatedY = x * Math.sin(rad) + y * Math.cos(rad);
  return { x: rotatedX, y: rotatedY };
};
