"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.replaceConfigTemplates = exports.getConfigFilePath = void 0;
const get_1 = __importDefault(require("lodash/get"));
const isPlainObject_1 = __importDefault(require("lodash/isPlainObject"));
const isUndefined_1 = __importDefault(require("lodash/isUndefined"));
const pick_1 = __importDefault(require("lodash/pick"));
const object_hash_1 = __importDefault(require("object-hash"));
const path_1 = __importDefault(require("path"));
const contracts_1 = require("./contracts");
/**
 * Returns full path to config file
 * For example - /home/user/config_folder/rdplibconfig.json - for NodeJS
 * /rdplibconfig.json - for a browser
 * @param {string} env Value of env variable RDPLIB_ENV
 * @param {string} dir Folder contains configuration files
 * @param {string} ext Config file extension (json,....)
 */
function getConfigFilePath(env = contracts_1.DEFAULT_CONFIG_PLATFORM, dir = contracts_1.DEFAULT_CONFIG_DIR, ext = contracts_1.DEFAULT_CONFIG_FILE_EXTENSION) {
    const fileName = `${contracts_1.DEFAULT_CONFIG_FILE_NAME}.${env}.${ext}`;
    return path_1.default.resolve(dir, fileName);
}
exports.getConfigFilePath = getConfigFilePath;
/**
 * Returns JSON with replaced string templates to appropriate values
 * If there are multiple references from template-to-template
 * file will be parsed recursively until all possible templates will be resolved
 * In case a template can't be resolved or does not exist - it leaves as is as string
 * @param {string} jsonAsString Source to be analyzed for replacing
 * @param {RegExp} search Regex to search for in the source file
 */
function replaceConfigTemplates(jsonAsString, search = contracts_1.CONFIG_TEMPLATE_TO_REPLACE) {
    const jsonContent = JSON.parse(jsonAsString);
    const withReplacedEnv = replaceTemplateValuesFromEnv(jsonAsString, search);
    const replacedTemplates = replaceTemplateValuesFromFile(withReplacedEnv, search);
    const result = JSON.parse(replacedTemplates);
    if ((0, object_hash_1.default)(jsonContent) !== (0, object_hash_1.default)(result)) {
        return replaceConfigTemplates(replacedTemplates, search);
    }
    return result;
}
exports.replaceConfigTemplates = replaceConfigTemplates;
/**
 * Search for all templates meeting the condition in Map
 * Returns the template as key and parsed paths to array of string as value
 * ${source:name:first} => ['source', 'name', 'first']
 * @param {string} source JSON file as a string
 * @param {Regex} regex Regex to find all the templates within the JSON file
 */
function getMatches(source, regex) {
    const result = new Map();
    let match;
    do {
        match = regex.exec(source);
        if (match) {
            result.set(match[0], match[1].split(contracts_1.CONFIG_TEMPLATE_DIVIDER));
        }
    } while (match);
    return result;
}
/**
 * Search for values inside the same JSON by passed paths
 * Returns a Map with template and value to replace this template within the JSON
 * {'${service:endpoint}' => 'http://hello.world'}
 * @param {string} source Config file content to replace templates with values
 * @param {RegExp} regex Regular expression to find a template(s) in the file
 */
function replaceTemplateValuesFromFile(source, regex) {
    const templateValues = new Map();
    const sourceAsJson = JSON.parse(source);
    const templatesMap = getMatches(source, regex);
    for (const [template, templatePath] of templatesMap) {
        const value = (0, pick_1.default)(sourceAsJson, templatePath);
        if (value && !(0, isUndefined_1.default)((0, get_1.default)(value, templatePath))) {
            const setValue = (0, get_1.default)(value, templatePath);
            const isObjectValue = (0, isPlainObject_1.default)(setValue);
            const templateToReplace = isObjectValue ? `"${template}"` : template;
            const valueToReplace = isObjectValue ? JSON.stringify(setValue) : setValue;
            templateValues.set(templateToReplace, valueToReplace);
        }
        else {
            templateValues.set(template, template);
        }
    }
    let result = source;
    templateValues.forEach((value, template) => {
        result = result.replace(template, value);
    });
    return result;
}
/**
 * Search for the template values in environment variables
 * The ENV variables have a higher priority than JSON file configurations
 * Returns a string with replaced values from ENV
 * {'${RDP_URL}' => 'http://hello.world'}
 * @param {string} source Source file as string
 * @param {RegExp} regex Regular expression to find a template(s) in the file
 */
function replaceTemplateValuesFromEnv(source, regex) {
    const templates = getMatches(source, regex);
    let result = source;
    for (const [template, paths] of templates) {
        const envName = paths.join(contracts_1.CONFIG_TEMPLATE_DIVIDER);
        const value = process.env[envName];
        if (value !== undefined) {
            result = result.replace(template, value);
        }
    }
    return result;
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uI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