"use strict";
var __spreadArrays = (this && this.__spreadArrays) || function () {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var rule_interface_1 = require("./interfaces/rule.interface");
var VersionForMessageFinder = /** @class */ (function () {
    function VersionForMessageFinder() {
    }
    VersionForMessageFinder.prototype.findBest = function (results, deprecatedVersion) {
        var supportedVersions = results
            .filter(function (result) { return result.action !== rule_interface_1.Action.deprecate; })
            .map(function (result) { return result.version; });
        return (this.findOldestWithSameMajorAndMinor(supportedVersions, deprecatedVersion) ||
            this.findLatestOfOldestSupportedMinor(supportedVersions, deprecatedVersion) ||
            this.findLatestOfOldestSupportedMajor(supportedVersions));
    };
    VersionForMessageFinder.prototype.findOldestWithSameMajorAndMinor = function (supportedVersions, deprecatedVersion) {
        var supportedVersionReversed = __spreadArrays(supportedVersions).reverse();
        for (var _i = 0, supportedVersionReversed_1 = supportedVersionReversed; _i < supportedVersionReversed_1.length; _i++) {
            var candidate = supportedVersionReversed_1[_i];
            if (candidate.major === deprecatedVersion.major &&
                candidate.minor === deprecatedVersion.minor) {
                return candidate;
            }
        }
        return undefined;
    };
    VersionForMessageFinder.prototype.findLatestOfOldestSupportedMinor = function (supportedVersions, deprecatedVersion) {
        var supportedVersionsOfSameMajor = supportedVersions.filter(function (version) { return version.major === deprecatedVersion.major; });
        var oldestSupported = supportedVersions.pop();
        if (!oldestSupported) {
            return undefined;
        }
        var supportedVersionsOfSameMinor = supportedVersionsOfSameMajor.filter(function (version) { return version.minor === oldestSupported.minor; });
        return supportedVersionsOfSameMinor[0];
    };
    VersionForMessageFinder.prototype.findLatestOfOldestSupportedMajor = function (supportedVersions) {
        var oldestSupported = supportedVersions.pop();
        if (!oldestSupported) {
            return undefined;
        }
        var supportedVersionsOfSameMajorAndMinor = supportedVersions.filter(function (version) {
            return version.major === oldestSupported.major &&
                version.minor === oldestSupported.minor;
        });
        return supportedVersionsOfSameMajorAndMinor[0];
    };
    return VersionForMessageFinder;
}());
exports.default = VersionForMessageFinder;
