import * as geolib from 'geolib';

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

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

    let crsOrthogonalOnOrigin;
    let crsOrthogonalOnEndpoint;
    if (turnDir === 'R') {
      crsOrthogonalOnOrigin = (crsIntoOrigin + 90).normaliseDegrees();
      crsOrthogonalOnEndpoint = (crsIntoEndpoint + 90).normaliseDegrees();
    } else {
      crsOrthogonalOnOrigin = (crsIntoOrigin - 90).normaliseDegrees();
      crsOrthogonalOnEndpoint = (crsIntoEndpoint - 90).normaliseDegrees();
    }

    const arcRad = geolib.getDistance(center, start);

    crsOrthogonalOnOrigin = crsOrthogonalOnOrigin.reciprocalCourse();
    crsOrthogonalOnEndpoint = crsOrthogonalOnEndpoint.reciprocalCourse();
    // Start turn immediately
    if (turnDir === 'R') {
      crsOrthogonalOnOrigin += crsOrthogonalOnOrigin < 1 ? crsOrthogonalOnOrigin : 1;
    } else {
      crsOrthogonalOnOrigin -= crsOrthogonalOnOrigin < 1 ? crsOrthogonalOnOrigin : 1;
    }

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

      const arcFix = geolib.computeDestinationPoint(center, arcRad, crsOrthogonalOnOrigin);

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

  return line;
};
