import * as geolib from 'geolib';
import { generateAFArc } from '../pathGenerators/generateAFArc.ts';
import { computeSpeed } from '../utils/computeSpeed.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: computeSpeed(leg, previousFix),
    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];
};
