import { __read, __spread } from "tslib";
import { children as calculateChildren } from "./Associates";
/**
 * Find the best fitting match from an array of approximately similar matches.
 * Choose the match that is deepest down the parent-child hierarchy,
 * e.g. if there are multiple matches at the same position in a parent-child constellation,
 * choose the match that belongs to the child.
 */
var BestMatch = /** @class */ (function () {
    function BestMatch(matches) {
        this.matches = matches;
        var secondRoots = matches.map(function (m) { return m.secondRootId; });
        this.roots = __spread(new Set(secondRoots));
    }
    BestMatch.prototype.best = function () {
        var root = this.preferredRoot();
        if (!root) {
            var _a = __read(this.matches, 1), first = _a[0];
            return first;
        }
        var result = this.matches.find(function (m) { return m.secondRootId === root; });
        return result;
    };
    BestMatch.prototype.preferredRoot = function () {
        var childrenMapped = this.roots.map(function (r) { return calculateChildren(r); });
        // make flat
        var children = childrenMapped.reduce(function (a, b) { return a.concat(b); }, new Array());
        // get intersection
        var intersectionBase = [children, this.roots];
        var ownChildren = intersectionBase.reduce(function (a, b) {
            return a.filter(function (c) { return b.indexOf(c) > -1; });
        });
        var _a = __read(ownChildren, 1), result = _a[0];
        return result;
    };
    return BestMatch;
}());
export { BestMatch };
