import { topsort, CycleException } from './topsort.js';

/**
 * @import { Graph } from '../graph.js';
 */

export { isAcyclic };

/**
 * Given a Graph, `g`, this function returns `true` if the
 * graph has no cycles and returns `false` if it does.
 *
 * @remarks
 * This algorithm returns
 * as soon as it detects the first cycle. You can use
 * {@link ../findCycles} to get the actual list of cycles in the
 * graph.
 *
 * @example
 *
 * ```js
 * var g = new graphlib.Graph();
 * g.setNode(1);
 * g.setNode(2);
 * g.setNode(3);
 * g.setEdge(1, 2);
 * g.setEdge(2, 3);
 *
 * graphlib.alg.isAcyclic(g);
 * // => true
 *
 * g.setEdge(3, 1);
 * graphlib.alg.isAcyclic(g);
 * // => false
 * ```
 *
 * @param {Graph} g - The graph to analyze.
 * @returns {boolean} `true` if the graph is acyclic, `false` otherwise.
 */
function isAcyclic(g) {
  try {
    topsort(g);
  } catch (e) {
    if (e instanceof CycleException) {
      return false;
    }
    throw e;
  }
  return true;
}
