import constant_default from "../../../lodash-es/constant.js";
import flatten_default from "../../../lodash-es/flatten.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 { List } from "./data/list.js";
var DEFAULT_WEIGHT_FN = constant_default(1);
function greedyFAS(e, i) {
	if (e.nodeCount() <= 1) return [];
	var o = buildState(e, i || DEFAULT_WEIGHT_FN);
	return flatten_default(map_default(doGreedyFAS(o.graph, o.buckets, o.zeroIdx), function(r) {
		return e.outEdges(r.v, r.w);
	}));
}
function doGreedyFAS(e, r, i) {
	for (var a = [], o = r[r.length - 1], s = r[0], c; e.nodeCount();) {
		for (; c = s.dequeue();) removeNode(e, r, i, c);
		for (; c = o.dequeue();) removeNode(e, r, i, c);
		if (e.nodeCount()) {
			for (var l = r.length - 2; l > 0; --l) if (c = r[l].dequeue(), c) {
				a = a.concat(removeNode(e, r, i, c, !0));
				break;
			}
		}
	}
	return a;
}
function removeNode(e, r, a, o, s) {
	var c = s ? [] : void 0;
	return forEach_default(e.inEdges(o.v), function(i) {
		var o = e.edge(i), l = e.node(i.v);
		s && c.push({
			v: i.v,
			w: i.w
		}), l.out -= o, assignBucket(r, a, l);
	}), forEach_default(e.outEdges(o.v), function(i) {
		var o = e.edge(i), s = i.w, c = e.node(s);
		c.in -= o, assignBucket(r, a, c);
	}), e.removeNode(o.v), c;
}
function buildState(e, r) {
	var a = new Graph(), l = 0, u = 0;
	forEach_default(e.nodes(), function(e) {
		a.setNode(e, {
			v: e,
			in: 0,
			out: 0
		});
	}), forEach_default(e.edges(), function(e) {
		var i = a.edge(e.v, e.w) || 0, o = r(e), s = i + o;
		a.setEdge(e.v, e.w, s), u = Math.max(u, a.node(e.v).out += o), l = Math.max(l, a.node(e.w).in += o);
	});
	var d = range_default(u + l + 3).map(function() {
		return new List();
	}), f = l + 1;
	return forEach_default(a.nodes(), function(e) {
		assignBucket(d, f, a.node(e));
	}), {
		graph: a,
		buckets: d,
		zeroIdx: f
	};
}
function assignBucket(e, r, i) {
	i.out ? i.in ? e[i.out - i.in + r].enqueue(i) : e[e.length - 1].enqueue(i) : e[0].enqueue(i);
}
export { greedyFAS };
