import * as geolib from "geolib";
import { handleTurnAtFix } from "../pathGenerators/handleTurnAtFix.ts";
import Parser from "../parser.ts";

export const TerminatorsTF = (
  leg: TFTerminalEntry,
  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 = geolib.getGreatCircleBearing(previousFix, targetFix);
  const line = handleTurnAtFix(
    crs,
    crs,
    lastCourse,
    previousFix,
    targetFix,
    leg.TurnDir
  );

  return [targetFix, line];
};
