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

export const TerminatorsRF = (
  leg: RFTerminalEntry,
  nextLeg: TerminalEntry,
  previousFix: NavFix,
  lastCourse: number,
  waypoint?: Waypoint
): [NavFix?, LineSegment[]?] => {
  const targetFix: NavFix = {
    latitude: leg.WptLat,
    longitude: leg.WptLon,
    name: waypoint?.Ident ?? undefined,
    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 [crs] = getCourseAndFixForIntercepts(nextLeg, previousFix);

  const line = generateRFArc(
    crs,
    lastCourse,
    previousFix,
    { latitude: leg.CenterLat, longitude: leg.CenterLon },
    leg.TurnDir
  );
  line.push([targetFix.longitude, targetFix.latitude]);

  return [targetFix, line];
};
