"use strict";
/*
 * Copyright © 2020 Atomist, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.sdmGoalTimeout = exports.mergeGoalData = exports.goalData = exports.goalKeyString = exports.goalKeyEquals = exports.mapKeyToGoal = void 0;
const configuration_1 = require("@atomist/automation-client/lib/configuration");
const sprintf_js_1 = require("sprintf-js");
function mapKeyToGoal(goals) {
    return (keyToFind) => {
        const found = goals.find(g => goalKeyEquals(g, keyToFind));
        return found;
    };
}
exports.mapKeyToGoal = mapKeyToGoal;
function goalKeyEquals(a, b) {
    return a.environment === b.environment &&
        a.uniqueName === b.uniqueName;
}
exports.goalKeyEquals = goalKeyEquals;
function goalKeyString(gk) {
    return sprintf_js_1.sprintf("%s in %s", gk.uniqueName, gk.environment);
}
exports.goalKeyString = goalKeyString;
/**
 * Read and parse goal event data.  If the goal event has no data,
 * return an empty object.  Note: this purposely only works if the
 * data field is stringified JSON.
 *
 * @param sdmGoal
 * @return JSON parsed goal event data property
 */
function goalData(sdmGoal) {
    if (!(sdmGoal === null || sdmGoal === void 0 ? void 0 : sdmGoal.data)) {
        return {};
    }
    let data;
    try {
        data = JSON.parse(sdmGoal.data);
    }
    catch (e) {
        e.message = `Failed to parse goal event data for ${sdmGoal.uniqueName} as JSON '${sdmGoal.data}': ${e.message}`;
        throw e;
    }
    return data;
}
exports.goalData = goalData;
/**
 * Return a shallow merge the provided `data` and the goal event data
 * property, parsed as JSON.  Properties in `data` take precedence
 * over those in the parsed goal event data object.
 *
 * @param data
 * @param sdmGoal
 * @return shallow merge of data and SDM goal event data property
 */
function mergeGoalData(data, sdmGoal) {
    return Object.assign(Object.assign({}, goalData(sdmGoal)), data);
}
exports.mergeGoalData = mergeGoalData;
/**
 * Return configured SDM goal timeout or default value, 10 minutes.
 */
function sdmGoalTimeout(cfg) {
    var _a, _b;
    return ((_b = (_a = cfg === null || cfg === void 0 ? void 0 : cfg.sdm) === null || _a === void 0 ? void 0 : _a.goal) === null || _b === void 0 ? void 0 : _b.timeout) || configuration_1.configurationValue("sdm.goal.timeout", 1000 * 60 * 10);
}
exports.sdmGoalTimeout = sdmGoalTimeout;
//# sourceMappingURL=sdmGoal.js.map