import * as geolib from 'geolib';
import { generatePerformanceArc } from './generatePerformanceArc.ts';
import { generateTangentArc } from './generateTangentArc.ts';

/**
 * @param crsIntoEndpoint Course into endpoint
 * @param crsIntoIntercept Course into intercept point (only fo intercept type legs)
 * @param crsFromOrigin Course from arc origin point
 * @param start Waypoint where leg starts
 * @param end Waypoint where leg ends
 * @param speed Speed for performance arc
 * @param turnDir Turn direction
 * @returns Line segments from `start` to `end`
 */
export const handleTurnAtFix = (
  crsIntoEndpoint: number,
  crsIntoIntercept: number,
  crsFromOrigin: number,
  start: NavFix,
  end: NavFix,
  speed: number,
  turnDir?: TurnDirection
) => {
  const line: LineSegment[] = [];

  // Overfly turn
  if (start.isFlyOver) {
    const arc1 = generateTangentArc(crsIntoEndpoint, crsFromOrigin, start, end, turnDir);

    const arc2 = generatePerformanceArc(crsIntoIntercept, crsFromOrigin, start, speed, turnDir);

    // Decide on arc
    let arc;
    if (arc1) {
      const endCrs = geolib.getGreatCircleBearing(
        {
          latitude: arc1.at(-1)![1],
          longitude: arc1.at(-1)![0],
        },
        end
      );

      if (endCrs <= crsIntoEndpoint + 1 && endCrs >= crsIntoEndpoint - 1) arc = arc1;
      else arc = arc2;
    } else {
      arc = arc2;
    }
    line.push(...arc);
    line.push([end.longitude, end.latitude]);
  }
  // FIXME: Procedural turn
  else {
    // Direct line for now
    line.push([start.longitude, start.latitude], [end.longitude, end.latitude]);
  }

  return line;
};
