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

// NOTE: No wind adjustments to be made, no clue how *that* would draw
// NOTE: Distance not adjusted for altitude in this demo
export const TerminatorsVD = (
  leg: VDTerminalEntry,
  previousFix: NavFix,
  lastCourse: number
): [NavFix?, LineSegment[]?] => {
  const navaid = {
    latitude: leg.NavLat,
    longitude: leg.NavLon,
  };
  const crsIntoEndpoint = leg.Course.toTrue(previousFix);
  const speed = computeSpeed(leg, previousFix);

  // Compute overfly
  const [line, arcEnd, _lastCourse] = generateOverflyArc(crsIntoEndpoint, lastCourse, previousFix, speed, leg.TurnDir);
  lastCourse = _lastCourse;

  // Compute distance to fly from arc end
  const crsToNavaid = geolib.getGreatCircleBearing(arcEnd, navaid);
  const distToNavaid = geolib.getDistance(arcEnd, navaid);
  let remainingDistance = leg.Distance.toMetre();
  // Navaid behind us
  if (Math.abs(crsToNavaid - lastCourse) > 90) {
    remainingDistance -= distToNavaid;
  }
  // Navaid in front of us
  else {
    // Navaid will not be passed before distance is hit
    if (distToNavaid > remainingDistance) remainingDistance = distToNavaid - remainingDistance;
  }

  // Compute intercept of crs from arc end and distance
  const targetFix: NavFix = {
    ...geolib.computeDestinationPoint(arcEnd, remainingDistance, lastCourse),
    name: leg.Distance.toString(),
    isFlyOver: true,
    altitude: leg.Alt ? leg.Alt.parseAltitude() : previousFix.altitude,
    speed: speed,
    speedConstraint: leg.SpeedLimit,
    altitudeConstraint: leg.Alt,
  };
  line.push([targetFix.longitude, targetFix.latitude]);

  return [targetFix, line];
};
