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

export const TerminatorsCR = (
  leg: CRTerminalEntry,
  previousFix: NavFix,
  lastCourse: number
): [NavFix?, LineSegment[]?] => {
  const crsIntoEndpoint = leg.Course.toTrue(previousFix);

  const interceptFix: NavFix = {
    ...computeIntersection(
      previousFix,
      crsIntoEndpoint,
      { latitude: leg.NavLat, longitude: leg.NavLon },
      leg.NavBear.toTrue({ latitude: leg.NavLat, longitude: leg.NavLon })
    )!,
    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(
    crsIntoEndpoint,
    leg.Course.toTrue(previousFix),
    lastCourse,
    previousFix,
    interceptFix,
    leg.TurnDir
  );

  return [interceptFix, line];
};
