'use strict';
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.processDirectives = processDirectives;
const hdbUtil = __importStar(require("../utility/common_utils.js"));
const harper_logger_ts_1 = __importDefault(require("../utility/logging/harper_logger.js"));
const directivesController = __importStar(require("./directives/directivesController.js"));
/**
 * Iterates through the directives files to find uninstalled updates and runs the files.
 *
 * @param upgradeObj
 * @returns {Promise<*[]>}
 */
async function processDirectives(upgradeObj) {
    console.log('Starting upgrade process...');
    let loadedDirectives = directivesController.getVersionsForUpgrade(upgradeObj);
    let upgradeDirectives = getUpgradeDirectivesToInstall(loadedDirectives);
    let allResponses = [];
    const dirLength = upgradeDirectives.length;
    for (let i = 0; i < dirLength; i++) {
        const vers = upgradeDirectives[i];
        let notifyMsg = `Running upgrade for version ${vers.version}`;
        harper_logger_ts_1.default.notify(notifyMsg);
        console.log(notifyMsg);
        let syncFuncResponse = [];
        let asyncFuncResponses = [];
        // Run sync functions for upgrade
        try {
            syncFuncResponse = runSyncFunctions(vers.sync_functions);
        }
        catch (e) {
            harper_logger_ts_1.default.error(`Error while running an upgrade script for ${vers.version}`);
            throw e;
        }
        // Run async functions for upgrade
        try {
            asyncFuncResponses = await runAsyncFunctions(vers.async_functions);
        }
        catch (e) {
            harper_logger_ts_1.default.error(`Error while running an upgrade script for ${vers.version}`);
            throw e;
        }
        allResponses.push(...syncFuncResponse, ...asyncFuncResponses);
    }
    return allResponses;
}
/**
 * Runs sync functions specified in a directive object.
 *
 * @param directiveFunctions - Array of sync functions to run
 * @returns - Array of responses from function calls
 */
function runSyncFunctions(directiveFunctions) {
    if (hdbUtil.isEmptyOrZeroLength(directiveFunctions)) {
        harper_logger_ts_1.default.info('No functions found to run for upgrade');
        return [];
    }
    if (!Array.isArray(directiveFunctions)) {
        harper_logger_ts_1.default.info('Passed parameter is not an array');
        return [];
    }
    let funcResponses = [];
    for (let func of directiveFunctions) {
        harper_logger_ts_1.default.info(`Running function ${func.name}`);
        if (!(func instanceof Function)) {
            harper_logger_ts_1.default.info('Variable being processed is not a function');
            continue;
        }
        const response = func();
        harper_logger_ts_1.default.info(response);
        funcResponses.push(response);
    }
    return funcResponses;
}
/**
 * Runs async functions specified in a directive object.
 *
 * @param directiveFunctions - Array of async functions to run
 * @returns - Array of responses from async function calls
 */
async function runAsyncFunctions(directiveFunctions) {
    if (hdbUtil.isEmptyOrZeroLength(directiveFunctions)) {
        harper_logger_ts_1.default.info('No functions found to run for upgrade');
        return [];
    }
    if (!Array.isArray(directiveFunctions)) {
        harper_logger_ts_1.default.info('Passed parameter is not an array');
        return [];
    }
    let funcResponses = [];
    const funcsLength = directiveFunctions.length;
    for (let i = 0; i < funcsLength; i++) {
        const func = directiveFunctions[i];
        harper_logger_ts_1.default.info(`Running function ${func.name}`);
        if (!(func instanceof Function)) {
            harper_logger_ts_1.default.info('Variable being processed is not a function');
            continue;
        }
        const response = await func();
        harper_logger_ts_1.default.info(response);
        funcResponses.push(response);
    }
    return funcResponses;
}
/**
 * Based on the current version, find all upgrade directives that need to be installed to make this installation current.
 * Returns the install directives array sorted from lowest to highest version number.
 *
 * @param currVersionNum - The current version of HDB.
 * @returns {Array}
 */
function getUpgradeDirectivesToInstall(loadedDirectives) {
    if (hdbUtil.isEmptyOrZeroLength(loadedDirectives)) {
        return [];
    }
    let versionModulesToRun = [];
    for (let vers of loadedDirectives) {
        let module = directivesController.getDirectiveByVersion(vers);
        if (module) {
            versionModulesToRun.push(module);
        }
    }
    return versionModulesToRun;
}
//# sourceMappingURL=directivesManager.js.map