"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.selectVersion = selectVersion;
const platform_utils_1 = require("./platform.utils");
/** Give a version to match and a set of ComponentWithVersion return the matching component */
function selectVersion(version, componentsToSelectFrom) {
    if (componentsToSelectFrom.length === 0) {
        return null;
    }
    // filter out components that don't match the current platform
    componentsToSelectFrom = componentsToSelectFrom.filter(c => platform_utils_1.ComponentPlatformUtils.matchesCurrentPlatform(c.filename));
    if (componentsToSelectFrom.length === 0) {
        throw new Error(`No versions found matching the current platform (${platform_utils_1.ComponentPlatformUtils.getCurrentPlatform()})`);
    }
    // filter by version
    if (version !== 'latest') {
        componentsToSelectFrom = componentsToSelectFrom.filter((comp) => comp.version === version);
    }
    componentsToSelectFrom.sort((a, b) => {
        // compare a.version and b.version by sem version
        const aVersion = a.version.split('.').map(Number);
        const bVersion = b.version.split('.').map(Number);
        for (let i = 0; i < Math.max(aVersion.length, bVersion.length); i++) {
            const aNum = aVersion[i] || 0;
            const bNum = bVersion[i] || 0;
            if (aNum !== bNum) {
                return bNum - aNum; // descending order
            }
        }
        // NOTE that we don't care if a release is stable or a prerelease, at this point - as pre-leases were allowed in the iocd config, meaning they should be considered valid
        // if both version have the same version compare by build number if present
        if (a.buildNumber !== undefined && b.buildNumber !== undefined) {
            // If both have build numbers, sort by build number descending
            return b.buildNumber - a.buildNumber;
        }
        else if (a.buildNumber !== undefined) {
            // a has build number, b doesn't -> we use b as we prefer non-build versions
            return 1;
        }
        else if (b.buildNumber !== undefined) {
            // b has build number, a doesn't -> we use a as we prefer non-build versions
            return -1;
        }
        // they are the same
        return 0;
    });
    return componentsToSelectFrom[0] || null;
}
//# sourceMappingURL=version.selector.js.map