"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.pendingGoalSets = exports.cancelGoalSetsCommand = exports.listPendingGoalSetsCommand = void 0;
const configuration_1 = require("@atomist/automation-client/lib/configuration");
const string_1 = require("@atomist/automation-client/lib/internal/util/string");
const GraphClient_1 = require("@atomist/automation-client/lib/spi/graph/GraphClient");
const MessageClient_1 = require("@atomist/automation-client/lib/spi/message/MessageClient");
const slack_messages_1 = require("@atomist/slack-messages");
const fetchGoalsOnCommit_1 = require("../../api-helper/goal/fetchGoalsOnCommit");
const storeGoals_1 = require("../../api-helper/goal/storeGoals");
const messages_1 = require("../../api-helper/misc/slack/messages");
const types_1 = require("../../typings/types");
/**
 * List all pending goal sets and allow to cancel
 * @param sdm
 */
function listPendingGoalSetsCommand(sdm) {
    return {
        name: "ListGoalSets",
        description: "List pending goal sets",
        parameters: {
            msgId: { required: false, displayable: false },
        },
        intent: `list goal sets ${sdm.configuration.name.replace("@", "")}`,
        listener: async (ci) => {
            const id = ci.parameters.msgId || string_1.guid();
            let offset = 0;
            let pgs = await pendingGoalSets(ci.context, sdm.configuration.name, offset);
            const attachments = [];
            while (pgs.length > 0) {
                for (const pg of pgs) {
                    attachments.push({
                        text: `Pending goal set ${slack_messages_1.italic(pg.goalSet)} ${slack_messages_1.codeLine(pg.goalSetId.slice(0, 7))} on ${slack_messages_1.codeLine(pg.sha.slice(0, 7))} of ${slack_messages_1.bold(`${pg.repo.owner}/${pg.repo.name}/${pg.branch}`)} is ${slack_messages_1.italic(pg.state)}`,
                        fallback: pg.goalSet,
                        actions: [
                            MessageClient_1.buttonForCommand({ text: "Cancel" }, cancelGoalSetsCommand(sdm).name, {
                                goalSetId: pg.goalSetId,
                                msgId: id,
                            }),
                        ],
                    });
                }
                offset = offset + pgs.length;
                pgs = await pendingGoalSets(ci.context, sdm.configuration.name, offset);
            }
            const update = MessageClient_1.buttonForCommand({ text: "Refresh" }, "ListGoalSets", { msgId: id });
            let msg;
            if (attachments.length > 0) {
                msg = messages_1.slackInfoMessage("Pending Goal Sets", `Following ${attachments.length} goal ${attachments.length === 1 ? "set is" : "sets are"} pending:`);
                msg.attachments[0].footer = undefined;
                msg.attachments[0].ts = undefined;
                msg.attachments.push(...attachments);
            }
            else {
                msg = messages_1.slackInfoMessage("Pending Goal Sets", `No pending goal sets found`);
            }
            const lastAttachment = msg.attachments[msg.attachments.length - 1];
            lastAttachment.footer = messages_1.slackFooter();
            lastAttachment.ts = messages_1.slackTs();
            if (lastAttachment.actions) {
                lastAttachment.actions.push(update);
            }
            else {
                lastAttachment.actions = [update];
            }
            await ci.context.messageClient.respond(msg, { id });
        },
    };
}
exports.listPendingGoalSetsCommand = listPendingGoalSetsCommand;
/**
 * Cancel one or all pending goal sets
 * @param sdm
 */
function cancelGoalSetsCommand(sdm) {
    return {
        name: "CancelGoalSets",
        description: "Cancel one or all pending goal sets of this SDM",
        intent: `cancel goal sets ${sdm.configuration.name.replace("@", "")}`,
        parameters: {
            goalSetId: { required: false, description: "ID of the goal set to cancel" },
            msgId: { required: false, displayable: false },
        },
        listener: async (ci) => {
            const id = ci.parameters.msgId || string_1.guid();
            if (!!ci.parameters.goalSetId) {
                await cancelGoalSet(ci.parameters.goalSetId, ci.context, id);
            }
            else {
                let pgs = await pendingGoalSets(ci.context, sdm.configuration.name);
                let count = 0;
                while (pgs.length > 0) {
                    for (const pg of pgs) {
                        await cancelGoalSet(pg.goalSetId, ci.context);
                        count++;
                    }
                    pgs = await pendingGoalSets(ci.context, sdm.configuration.name);
                }
                await ci.context.messageClient.respond(messages_1.slackSuccessMessage("Cancel Goal Sets", `Successfully canceled ${count} pending goal ${count > 1 ? "sets" : "set"}`));
            }
        },
    };
}
exports.cancelGoalSetsCommand = cancelGoalSetsCommand;
async function pendingGoalSets(ctx, name, offset = 0, fetch = 50) {
    const results = await ctx.graphClient.query({
        name: "InProcessSdmGoalSets",
        variables: {
            fetch,
            offset,
            registration: [name],
        },
        options: Object.assign(Object.assign({}, GraphClient_1.QueryNoCacheOptions), { log: configuration_1.configurationValue("sdm.query.logging", false) }),
    });
    return (results.SdmGoalSet || []).map(gs => gs);
}
exports.pendingGoalSets = pendingGoalSets;
async function cancelGoalSet(goalSetId, ctx, id) {
    const result = await ctx.graphClient.query({
        name: "SdmGoalSetForId",
        variables: {
            goalSetId: [goalSetId],
        },
        options: GraphClient_1.QueryNoCacheOptions,
    });
    const goalSet = result.SdmGoalSet[0];
    const goals = await fetchGoalsOnCommit_1.fetchGoalsForCommit(ctx, {
        owner: goalSet.repo.owner,
        repo: goalSet.repo.name,
        sha: goalSet.sha,
        branch: goalSet.branch,
    }, goalSet.repo.providerId, goalSetId);
    for (const goal of goals) {
        if (![types_1.SdmGoalState.success,
            types_1.SdmGoalState.canceled,
            types_1.SdmGoalState.stopped,
            types_1.SdmGoalState.skipped,
            types_1.SdmGoalState.failure].includes(goal.state)) {
            await storeGoals_1.updateGoal(ctx, goal, {
                state: types_1.SdmGoalState.canceled,
                description: !!goal.descriptions && !!goal.descriptions.canceled
                    ? goal.descriptions.canceled : `Canceled: ${goal.name}`,
            });
        }
    }
    if (result && result.SdmGoalSet && result.SdmGoalSet.length === 1) {
        const gs = result.SdmGoalSet[0];
        const newGoalSet = Object.assign(Object.assign({}, gs), { state: types_1.SdmGoalState.canceled });
        await storeGoals_1.storeGoalSet(ctx, newGoalSet);
    }
    await ctx.messageClient.respond(messages_1.slackInfoMessage("Cancel Goal Set", `Canceled goal set ${slack_messages_1.italic(goalSet.goalSet)} ${slack_messages_1.codeLine(goalSetId.slice(0, 7))} on ${slack_messages_1.codeLine(goalSet.sha.slice(0, 7))} of ${slack_messages_1.bold(`${goalSet.repo.owner}/${goalSet.repo.name}/${goalSet.branch}`)}`), { id });
}
//# sourceMappingURL=cancelGoals.js.map