"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.invokeConfigurer = exports.convertGoalData = exports.configure = void 0;
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const _ = require("lodash");
const goalDsl_1 = require("../../api/dsl/goalDsl");
const Goals_1 = require("../../api/goal/Goals");
const goalTest_1 = require("../../api/mapping/goalTest");
const commonPushTests_1 = require("../../api/mapping/support/commonPushTests");
const pushTestUtils_1 = require("../../api/mapping/support/pushTestUtils");
const array_1 = require("../util/misc/array");
const configureSdm_1 = require("./configureSdm");
const machineFactory_1 = require("./machineFactory");
/**
 * Function to create an SDM configuration constant to be exported from an index.ts/js.
 */
function configure(configurer, options = {}) {
    return {
        postProcessors: [
            configureSdm_1.configureSdm(async (cfg) => {
                let cfgToUse = cfg;
                // Modify the configuration before creating the SDM instance
                if (!!options.preProcessors) {
                    for (const preProcessor of array_1.toArray(options.preProcessors)) {
                        cfgToUse = await preProcessor(cfgToUse);
                    }
                }
                const sdm = machineFactory_1.createSoftwareDeliveryMachine({
                    name: options.name || cfgToUse.name,
                    configuration: cfgToUse,
                });
                const configured = await invokeConfigurer(sdm, configurer);
                if (Array.isArray(configured)) {
                    sdm.withPushRules(configured[0], ...configured.slice(1));
                }
                else if (!!configured) {
                    const goalContributions = convertGoalData(configured);
                    if (goalContributions.length > 0) {
                        sdm.withPushRules(goalContributions[0], ...(goalContributions.slice(1) || []));
                    }
                }
                return sdm;
            }, options),
            ...array_1.toArray(options.postProcessors || []),
        ],
    };
}
exports.configure = configure;
/**
 * Convert the provided GoalData instance into an array of GoalContributions
 */
function convertGoalData(goalData) {
    const goalContributions = [];
    _.forEach(goalData, (v, k) => {
        v.__goals = [];
        const gs = Goals_1.goals(k.replace(/_/g, " "));
        let lg;
        if (!!v.dependsOn) {
            lg = [];
            array_1.toArray(v.dependsOn).forEach(d => {
                if (typeof d === "string") {
                    if (!!goalData[d] && !!goalData[d].__goals) {
                        lg.push(...goalData[d].__goals);
                    }
                    else {
                        throw new Error(`Provided dependsOn goals with name '${d}' do not exist or is after current goals named '${k}'`);
                    }
                }
                else {
                    lg.push(...array_1.toArray(d));
                }
            });
        }
        array_1.toArray(v.goals || []).forEach(g => {
            v.__goals.push(...(Array.isArray(g) ? g : [g]));
            if (!!lg) {
                gs.plan(...convertGoals(g)).after(...convertGoals(lg));
            }
            else {
                gs.plan(...convertGoals(g));
            }
            lg = array_1.toArray(g);
        });
        goalContributions.push(goalDsl_1.whenPushSatisfies(convertPushTest(v.test)).setGoals(gs));
    });
    return goalContributions;
}
exports.convertGoalData = convertGoalData;
/**
 * Invoke the given configurer
 */
async function invokeConfigurer(sdm, configurer) {
    try {
        // Decorate the createGoals method onto the SDM
        sdm.createGoals = async (creator, configurers) => {
            let gc;
            try {
                gc = await creator(sdm);
            }
            catch (e) {
                e.message = `Creating goals failed: ${e.message}`;
                logger_1.logger.error(e.message);
                throw e;
            }
            try {
                if (!!configurers) {
                    for (const c of array_1.toArray(configurers)) {
                        await c(sdm, gc);
                    }
                }
            }
            catch (e) {
                e.message = `Configuring goals failed: ${e.message}`;
                logger_1.logger.error(e.message);
                throw e;
            }
            return gc;
        };
        return await configurer(sdm);
    }
    finally {
        delete sdm.createGoals;
    }
}
exports.invokeConfigurer = invokeConfigurer;
function convertPushTest(test) {
    if (Array.isArray(test)) {
        const goalPushTests = test.filter(t => !!t.pushTest);
        const convertedPushTest = pushTestUtils_1.allSatisfied(...test.map(wrapTest));
        if (goalPushTests.length > 0) {
            convertedPushTest.pushTest = pushTestUtils_1.allSatisfied(...goalPushTests.map(t => t.pushTest));
        }
        return convertedPushTest;
    }
    else {
        return wrapTest(test || commonPushTests_1.AnyPush);
    }
}
function wrapTest(test) {
    if (!!test.pushTest) {
        return test;
    }
    else {
        return goalTest_1.notGoalOrOutputTest(test);
    }
}
function convertGoals(gs) {
    if (Array.isArray(gs)) {
        return gs;
    }
    else {
        return [gs];
    }
}
//# sourceMappingURL=configure.js.map