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

export const TerminatorsAF = (
  leg: AFTerminalEntry,
  previousFix: NavFix,
  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 arcEndCrs = geolib.getGreatCircleBearing(
    {
      latitude: leg.NavLat,
      longitude: leg.NavLon,
    },
    {
      latitude: leg.WptLat,
      longitude: leg.WptLon,
    }
  );
  const line = generateAFArc(
    arcEndCrs,
    leg.Course.toTrue({ latitude: leg.NavLat, longitude: leg.NavLon }),
    previousFix,
    { latitude: leg.NavLat, longitude: leg.NavLon },
    leg.NavDist,
    leg.TurnDir
  );

  return [targetFix, line];
};
