import forEach_default from "../../../lodash-es/forEach.js";
import values_default from "../../../lodash-es/values.js";
import max_default from "../../../lodash-es/max.js";
import reduce_default from "../../../lodash-es/reduce.js";
import { addBorderNode, addDummyNode } from "./util.js";
function run(i) {
	var a = addDummyNode(i, "root", {}, "_root"), s = treeDepths(i), u = max_default(values_default(s)) - 1, d = 2 * u + 1;
	i.graph().nestingRoot = a, forEach_default(i.edges(), function(e) {
		i.edge(e).minlen *= d;
	});
	var f = sumWeights(i) + 1;
	forEach_default(i.children(), function(e) {
		dfs(i, a, d, f, u, s, e);
	}), i.graph().nodeRankFactor = d;
}
function dfs(n, r, i, o, s, c, l) {
	var u = n.children(l);
	if (!u.length) {
		l !== r && n.setEdge(r, l, {
			weight: 0,
			minlen: i
		});
		return;
	}
	var d = addBorderNode(n, "_bt"), f = addBorderNode(n, "_bb"), p = n.node(l);
	n.setParent(d, l), p.borderTop = d, n.setParent(f, l), p.borderBottom = f, forEach_default(u, function(e) {
		dfs(n, r, i, o, s, c, e);
		var a = n.node(e), u = a.borderTop ? a.borderTop : e, p = a.borderBottom ? a.borderBottom : e, m = a.borderTop ? o : 2 * o, h = u === p ? s - c[l] + 1 : 1;
		n.setEdge(d, u, {
			weight: m,
			minlen: h,
			nestingEdge: !0
		}), n.setEdge(p, f, {
			weight: m,
			minlen: h,
			nestingEdge: !0
		});
	}), n.parent(l) || n.setEdge(r, d, {
		weight: 0,
		minlen: s + c[l]
	});
}
function treeDepths(n) {
	var r = {};
	function i(a, o) {
		var s = n.children(a);
		s && s.length && forEach_default(s, function(e) {
			i(e, o + 1);
		}), r[a] = o;
	}
	return forEach_default(n.children(), function(e) {
		i(e, 1);
	}), r;
}
function sumWeights(e) {
	return reduce_default(e.edges(), function(n, r) {
		return n + e.edge(r).weight;
	}, 0);
}
function cleanup(n) {
	var r = n.graph();
	n.removeNode(r.nestingRoot), delete r.nestingRoot, forEach_default(n.edges(), function(e) {
		n.edge(e).nestingEdge && n.removeEdge(e);
	});
}
export { cleanup, run };
