import getGreatCircleBearing from 'geolib/es/getGreatCircleBearing';
import { generateAFArc } from '../pathGenerators/generateAFArc';
import { computeSpeed } from '../utils/computeSpeed';

export const TerminatorsAF = (
  leg: AFTerminalEntry,
  previousFix: NavFix,
  waypoint?: Waypoint
): [NavFix?, LineSegment[]?] => {
  const navaid = {
    latitude: leg.NavLat,
    longitude: leg.NavLon,
  };

  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: computeSpeed(leg, previousFix),
    speedConstraint: leg.SpeedLimit,
    altitudeConstraint: leg.Alt,
    IsFAF: leg.IsFAF,
    IsMAP: leg.IsMAP,
  };

  const arcEndCrs = getGreatCircleBearing(navaid, targetFix);

  const line = generateAFArc(arcEndCrs, leg.Course.toTrue(navaid), previousFix, navaid, leg.NavDist, leg.TurnDir);

  return [targetFix, line];
};
