import cloneDeep_default from "../../../../lodash-es/cloneDeep.js";
import forEach_default from "../../../../lodash-es/forEach.js";
import map_default from "../../../../lodash-es/map.js";
import range_default from "../../../../lodash-es/range.js";
import { Graph } from "../../graphlib/graph.js";
import "../../graphlib/index.js";
import { buildLayerMatrix, maxRank } from "../util.js";
import { addSubgraphConstraints } from "./add-subgraph-constraints.js";
import { buildLayerGraph } from "./build-layer-graph.js";
import { crossCount } from "./cross-count.js";
import { initOrder } from "./init-order.js";
import { sortSubgraph } from "./sort-subgraph.js";
function order(s) {
	var c = maxRank(s), u = buildLayerGraphs(s, range_default(1, c + 1), "inEdges"), f = buildLayerGraphs(s, range_default(c - 1, -1, -1), "outEdges"), p = initOrder(s);
	assignOrder(s, p);
	for (var m = Infinity, h, g = 0, _ = 0; _ < 4; ++g, ++_) {
		sweepLayerGraphs(g % 2 ? u : f, g % 4 >= 2), p = buildLayerMatrix(s);
		var v = crossCount(s, p);
		v < m && (_ = 0, h = cloneDeep_default(p), m = v);
	}
	assignOrder(s, h);
}
function buildLayerGraphs(e, s, l) {
	return map_default(s, function(s) {
		return buildLayerGraph(e, s, l);
	});
}
function sweepLayerGraphs(e, c) {
	var l = new Graph();
	forEach_default(e, function(e) {
		var u = e.graph().root, d = sortSubgraph(e, u, l, c);
		forEach_default(d.vs, function(s, c) {
			e.node(s).order = c;
		}), addSubgraphConstraints(e, l, d.vs);
	});
}
function assignOrder(e, c) {
	forEach_default(c, function(c) {
		forEach_default(c, function(s, c) {
			e.node(s).order = c;
		});
	});
}
export { order };
