import { handleTurnAtFix } from '../pathGenerators/handleTurnAtFix.ts';
import { computeIntersection } from '../utils/computeIntersection.ts';
import { computeSpeed } from '../utils/computeSpeed.ts';
import { getCourseAndFixForIntercepts } from '../utils/getCourseAndFixForIntercepts.ts';

// NOTE: No wind adjustments to be made, no clue how *that* would draw
export const TerminatorsVI = (
  leg: VITerminalEntry,
  nextLeg: TerminalEntry,
  previousFix: NavFix,
  lastCourse: number
): [NavFix?, LineSegment[]?] => {
  const [crs, nextFix] = getCourseAndFixForIntercepts(nextLeg, previousFix);
  const speed = computeSpeed(leg, previousFix);

  // Compute INTC
  const interceptFix: NavFix = {
    ...computeIntersection(previousFix, leg.Course.toTrue(nextFix), nextFix, crs)!,
    isFlyOver: leg.IsFlyOver,
    altitude: leg.Alt ? leg.Alt.parseAltitude() : previousFix.altitude,
    speed: speed,
    speedConstraint: leg.SpeedLimit,
    altitudeConstraint: leg.Alt,
  };

  const line = handleTurnAtFix(
    crs,
    leg.Course.toTrue(nextFix),
    lastCourse,
    previousFix,
    interceptFix,
    speed,
    leg.TurnDir
  );

  // Intercept based on previous intercept
  const interceptPoint2 = computeIntersection(
    { latitude: line.at(-2)![1], longitude: line.at(-2)![0] },
    leg.Course.toTrue(nextFix),
    nextFix,
    crs
  );
  if (interceptPoint2)
    return [
      { ...interceptFix, ...interceptPoint2 },
      [...line.slice(0, -1), [interceptPoint2.longitude, interceptPoint2.latitude]],
    ];

  return [interceptFix, line];
};
