import Parser from "../parser.ts";
import { handleTurnAtFix } from "../pathGenerators/handleTurnAtFix.ts";
import { computeIntersection } from "../utils/computeIntersection.ts";
import { getCourseAndFixForIntercepts } from "../utils/getCourseAndFixForIntercepts.ts";

export const TerminatorsCI = (
  leg: CITerminalEntry,
  nextLeg: TerminalEntry,
  previousFix: NavFix,
  lastCourse: number
): [NavFix?, LineSegment[]?] => {
  const [crs, nextFix] = getCourseAndFixForIntercepts(nextLeg, previousFix);

  // Compute INTC
  const interceptFix: NavFix = {
    ...computeIntersection(
      previousFix,
      leg.Course.toTrue(nextFix),
      nextFix,
      crs
    )!,
    isFlyOver: leg.IsFlyOver,
    altitude: leg.Alt ? leg.Alt.parseAltitude() : previousFix.altitude,
    speed: leg.SpeedLimit
      ? leg.SpeedLimit > Parser.AC_SPEED
        ? Parser.AC_SPEED
        : leg.SpeedLimit
      : previousFix.speed
      ? previousFix.speed
      : Parser.AC_SPEED,
    speedConstraint: leg.SpeedLimit,
    altitudeConstraint: leg.Alt,
  };

  const line = handleTurnAtFix(
    crs,
    leg.Course.toTrue(nextFix),
    lastCourse,
    previousFix,
    interceptFix,
    leg.TurnDir
  );

  // Intercept based on previous intercept
  const interceptPoint2 = computeIntersection(
    { latitude: line.at(-2)![1], longitude: line.at(-2)![0] },
    leg.Course.toTrue(nextFix),
    nextFix,
    crs
  );
  if (interceptPoint2)
    return [
      { ...interceptFix, ...interceptPoint2 },
      [
        ...line.slice(0, -1),
        [interceptPoint2.longitude, interceptPoint2.latitude],
      ],
    ];

  return [interceptFix, line];
};
