"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.
 */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SkipDownstreamGoalsOnGoalFailure = void 0;
const decorators_1 = require("@atomist/automation-client/lib/decorators");
const globals_1 = require("@atomist/automation-client/lib/globals");
const graphQL_1 = require("@atomist/automation-client/lib/graph/graphQL");
const HandlerResult_1 = require("@atomist/automation-client/lib/HandlerResult");
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const fetchGoalsOnCommit_1 = require("../../../../../api-helper/goal/fetchGoalsOnCommit");
const sdmGoal_1 = require("../../../../../api-helper/goal/sdmGoal");
const storeGoals_1 = require("../../../../../api-helper/goal/storeGoals");
const types_1 = require("../../../../../typings/types");
const validateGoal_1 = require("../../../../delivery/goals/support/validateGoal");
const goalSigning_1 = require("../../../../signing/goalSigning");
/**
 * Skip downstream goals on failed or stopped goal
 */
let SkipDownstreamGoalsOnGoalFailure = class SkipDownstreamGoalsOnGoalFailure {
    async handle(event, context) {
        const failedGoal = event.data.SdmGoal[0];
        if (!validateGoal_1.shouldHandle(failedGoal)) {
            logger_1.logger.debug(`Goal ${failedGoal.uniqueName} skipped because not managed by this SDM`);
            return HandlerResult_1.Success;
        }
        await goalSigning_1.verifyGoal(failedGoal, this.configuration.sdm.goalSigning, context);
        const goals = fetchGoalsOnCommit_1.fetchGoalsFromPush(failedGoal);
        const goalsToSkip = goals.filter(g => isDependentOn(failedGoal, g, sdmGoal_1.mapKeyToGoal(goals)))
            .filter(g => g.state === "planned");
        let failedGoalState;
        let failedGoalDescription;
        switch (failedGoal.state) {
            case types_1.SdmGoalState.failure:
                failedGoalDescription = "failed";
                failedGoalState = types_1.SdmGoalState.skipped;
                break;
            case types_1.SdmGoalState.stopped:
                failedGoalDescription = "stopped goals";
                failedGoalState = types_1.SdmGoalState.skipped;
                break;
            case types_1.SdmGoalState.canceled:
                failedGoalDescription = "was canceled";
                failedGoalState = types_1.SdmGoalState.canceled;
                break;
        }
        await Promise.all(goalsToSkip.map(g => storeGoals_1.updateGoal(context, g, {
            state: failedGoalState,
            description: `${failedGoalState === types_1.SdmGoalState.skipped ? "Skipped" : "Canceled"} ${g.name} because ${failedGoal.name} ${failedGoalDescription}`,
        })));
        return HandlerResult_1.Success;
    }
};
__decorate([
    decorators_1.Value(""),
    __metadata("design:type", Object)
], SkipDownstreamGoalsOnGoalFailure.prototype, "configuration", void 0);
SkipDownstreamGoalsOnGoalFailure = __decorate([
    decorators_1.EventHandler("Skip downstream goals on failed, stopped or canceled goal", () => graphQL_1.subscription({
        name: "OnAnyFailedSdmGoal",
        variables: { registration: () => { var _a, _b; return [(_b = (_a = globals_1.automationClientInstance()) === null || _a === void 0 ? void 0 : _a.configuration) === null || _b === void 0 ? void 0 : _b.name]; } },
    }))
], SkipDownstreamGoalsOnGoalFailure);
exports.SkipDownstreamGoalsOnGoalFailure = SkipDownstreamGoalsOnGoalFailure;
function isDependentOn(failedGoal, goal, preconditionToGoal) {
    if (!goal) {
        return false;
    }
    if (!goal.preConditions || goal.preConditions.length === 0) {
        return false; // no preconditions? not dependent
    }
    if (sdmGoal_1.mapKeyToGoal(goal.preConditions)(failedGoal)) {
        return true; // the failed goal is one of my preconditions? dependent
    }
    // otherwise, recurse on my preconditions
    return !!goal.preConditions
        .map(precondition => isDependentOn(failedGoal, preconditionToGoal(precondition), preconditionToGoal))
        .find(a => a); // if one is true, return true
}
//# sourceMappingURL=SkipDownstreamGoalsOnGoalFailure.js.map