import * as geolib from 'geolib';
import { generateOverflyArc } from '../pathGenerators/generateOverflyArc.ts';
import { computeSpeed } from '../utils/computeSpeed.ts';

export const TerminatorsDF = (
  leg: DFTerminalEntry,
  previousFix: NavFix,
  lastCourse: number,
  waypoint?: Waypoint
): [NavFix?, LineSegment[]?] => {
  const speed = computeSpeed(leg, previousFix);

  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: speed,
    speedConstraint: leg.SpeedLimit,
    altitudeConstraint: leg.Alt,
  };

  const crsIntoEndpoint = geolib.getGreatCircleBearing(previousFix, targetFix);

  // Compute overfly
  const [line, _, _lastCourse] = generateOverflyArc(
    crsIntoEndpoint,
    lastCourse,
    previousFix,
    speed,
    leg.TurnDir,
    previousFix.latitude.equal(targetFix.latitude) && previousFix.longitude.equal(targetFix.longitude)
  );
  lastCourse = _lastCourse;

  line.push([targetFix.longitude, targetFix.latitude]);

  return [targetFix, line];
};
