import * as geolib from 'geolib';

/**
 * @param crsIntoEndpoint Course into arc endpoint
 * @param crsFromOrigin Course into arc origin point
 * @param start Arc origin point
 * @param center Arc center point
 * @param radius Arc radius in nmi
 * @param turnDir
 * @returns Line segments
 */
export const generateAFArc = (
  crsIntoEndpoint: number,
  crsFromOrigin: number,
  start: NavFix,
  center: NavFix,
  radius: number,
  turnDir: TurnDirection
) => {
  const line: LineSegment[] = [[start.longitude, start.latitude]];

  if (crsIntoEndpoint !== crsFromOrigin) {
    // Turn Dir
    if (!turnDir || turnDir === 'E') {
      let prov = crsFromOrigin - crsIntoEndpoint;
      prov = prov > 180 ? prov - 360 : prov <= -180 ? prov + 360 : prov;
      turnDir = prov > 0 ? 'L' : 'R';
    }

    while (crsFromOrigin !== crsIntoEndpoint) {
      if (turnDir === 'R') {
        const delta = (crsIntoEndpoint - crsFromOrigin).normaliseDegrees();
        crsFromOrigin += delta < 1 ? delta : 1;
        crsFromOrigin = crsFromOrigin.normaliseDegrees();
      } else {
        const delta = (crsFromOrigin - crsIntoEndpoint).normaliseDegrees();
        crsFromOrigin -= delta < 1 ? delta : 1;
        crsFromOrigin = crsFromOrigin.normaliseDegrees();
      }
      if (crsFromOrigin === crsIntoEndpoint) break;

      const arcFix = geolib.computeDestinationPoint(center, radius.toMetre(), crsFromOrigin);

      line.push([arcFix.longitude, arcFix.latitude]);
    }
  }

  return line;
};
