import { Graph } from "./src-graphlib-graph.js";
import { maxRank, buildLayerMatrix } from "./src-dagre-util.js";
import { addSubgraphConstraints } from "./src-dagre-order-add-subgraph-constraints.js";
import { buildLayerGraph } from "./src-dagre-order-build-layer-graph.js";
import { crossCount } from "./src-dagre-order-cross-count.js";
import { initOrder } from "./src-dagre-order-init-order.js";
import { sortSubgraph } from "./src-dagre-order-sort-subgraph.js";
import range from "../lodash-es/range.js";
import cloneDeep from "../lodash-es/cloneDeep.js";
import map from "../lodash-es/map.js";
import forEach from "../lodash-es/forEach.js";
function order(g) {
  var maxRank$1 = maxRank(g), downLayerGraphs = buildLayerGraphs(g, range(1, maxRank$1 + 1), "inEdges"), upLayerGraphs = buildLayerGraphs(g, range(maxRank$1 - 1, -1, -1), "outEdges");
  var layering = initOrder(g);
  assignOrder(g, layering);
  var bestCC = Number.POSITIVE_INFINITY, best;
  for (var i = 0, lastBest = 0; lastBest < 4; ++i, ++lastBest) {
    sweepLayerGraphs(i % 2 ? downLayerGraphs : upLayerGraphs, i % 4 >= 2);
    layering = buildLayerMatrix(g);
    var cc = crossCount(g, layering);
    if (cc < bestCC) {
      lastBest = 0;
      best = cloneDeep(layering);
      bestCC = cc;
    }
  }
  assignOrder(g, best);
}
function buildLayerGraphs(g, ranks, relationship) {
  return map(ranks, function(rank) {
    return buildLayerGraph(g, rank, relationship);
  });
}
function sweepLayerGraphs(layerGraphs, biasRight) {
  var cg = new Graph();
  forEach(layerGraphs, function(lg) {
    var root = lg.graph().root;
    var sorted = sortSubgraph(lg, root, cg, biasRight);
    forEach(sorted.vs, function(v, i) {
      lg.node(v).order = i;
    });
    addSubgraphConstraints(lg, cg, sorted.vs);
  });
}
function assignOrder(g, layering) {
  forEach(layering, function(layer) {
    forEach(layer, function(v, i) {
      g.node(v).order = i;
    });
  });
}
export {
  order
};
//# sourceMappingURL=src-dagre-order-index.js.map
