import flatten_default from "../../../../lodash-es/flatten.js";
import forEach_default from "../../../../lodash-es/forEach.js";
import filter_default from "../../../../lodash-es/filter.js";
import isUndefined_default from "../../../../lodash-es/isUndefined.js";
import { barycenter } from "./barycenter.js";
import { resolveConflicts } from "./resolve-conflicts.js";
import { sort } from "./sort.js";
function sortSubgraph(l, u, d, f) {
	var p = l.children(u), m = l.node(u), h = m ? m.borderLeft : void 0, g = m ? m.borderRight : void 0, _ = {};
	h && (p = filter_default(p, function(e) {
		return e !== h && e !== g;
	}));
	var v = barycenter(l, p);
	forEach_default(v, function(e) {
		if (l.children(e.v).length) {
			var s = sortSubgraph(l, e.v, d, f);
			_[e.v] = s, Object.prototype.hasOwnProperty.call(s, "barycenter") && mergeBarycenters(e, s);
		}
	});
	var y = resolveConflicts(v, d);
	expandSubgraphs(y, _);
	var b = sort(y, f);
	if (h && (b.vs = flatten_default([
		h,
		b.vs,
		g
	]), l.predecessors(h).length)) {
		var x = l.node(l.predecessors(h)[0]), S = l.node(l.predecessors(g)[0]);
		Object.prototype.hasOwnProperty.call(b, "barycenter") || (b.barycenter = 0, b.weight = 0), b.barycenter = (b.barycenter * b.weight + x.order + S.order) / (b.weight + 2), b.weight += 2;
	}
	return b;
}
function expandSubgraphs(c, l) {
	forEach_default(c, function(s) {
		s.vs = flatten_default(s.vs.map(function(e) {
			return l[e] ? l[e].vs : e;
		}));
	});
}
function mergeBarycenters(e, s) {
	isUndefined_default(e.barycenter) ? (e.barycenter = s.barycenter, e.weight = s.weight) : (e.barycenter = (e.barycenter * e.weight + s.barycenter * s.weight) / (e.weight + s.weight), e.weight += s.weight);
}
export { sortSubgraph };
