import * as geolib from "geolib";
import Parser from "../parser.ts";

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

  // Check if there even is an arc
  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";
    }

    // Generate arc
    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();
      }

      const arcFix = geolib.computeDestinationPoint(
        {
          latitude: line.at(-1)![1],
          longitude: line.at(-1)![0],
        },
        (Parser.AC_SPEED / 3600).toMetre(),
        crsFromOrigin
      );

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

  return line;
};
