"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.updateGoalStateCommand = void 0;
const decorators_1 = require("@atomist/automation-client/lib/decorators");
const HandlerResult_1 = require("@atomist/automation-client/lib/HandlerResult");
const string_1 = require("@atomist/automation-client/lib/internal/util/string");
const GraphClient_1 = require("@atomist/automation-client/lib/spi/graph/GraphClient");
const slack_messages_1 = require("@atomist/slack-messages");
const _ = require("lodash");
const storeGoals_1 = require("../../api-helper/goal/storeGoals");
const messages_1 = require("../../api-helper/misc/slack/messages");
const ParametersDefinition_1 = require("../../api/registration/ParametersDefinition");
const types_1 = require("../../typings/types");
function updateGoalStateCommand() {
    return {
        name: "UpdateGoalStateCommand",
        description: "Update goal state",
        parameters: {
            goalSetId: {},
            uniqueName: {},
            state: {},
            msgId: {},
            slackRequester: {
                uri: decorators_1.MappedParameters.SlackUserName,
                required: false,
                declarationType: ParametersDefinition_1.DeclarationType.Mapped,
            },
            githubRequester: {
                uri: decorators_1.MappedParameters.GitHubUserLogin,
                required: false,
                declarationType: ParametersDefinition_1.DeclarationType.Mapped,
            },
            teamId: { uri: decorators_1.MappedParameters.SlackTeam, required: false, declarationType: ParametersDefinition_1.DeclarationType.Mapped },
            channelId: { uri: decorators_1.MappedParameters.SlackChannel, required: false, declarationType: ParametersDefinition_1.DeclarationType.Mapped },
        },
        listener: async (ci) => {
            const goalResult = await ci.context.graphClient.query({
                name: "SdmGoalsByGoalSetIdAndUniqueName",
                variables: {
                    goalSetId: [ci.parameters.goalSetId],
                    uniqueName: [ci.parameters.uniqueName],
                },
                options: GraphClient_1.QueryNoCacheOptions,
            });
            if (!goalResult || !goalResult.SdmGoal[0]) {
                await ci.context.messageClient.respond(messages_1.slackErrorMessage(`Update Goal State`, "Provided goal does not exist", ci.context));
                return HandlerResult_1.Success;
            }
            const goal = _.cloneDeep(goalResult.SdmGoal[0]);
            const actx = ci.context;
            const prov = {
                name: actx.context.operation,
                registration: actx.context.name,
                version: actx.context.version,
                correlationId: actx.context.correlationId,
                ts: Date.now(),
                channelId: ci.parameters.channelId,
                userId: ci.parameters.slackRequester ? ci.parameters.slackRequester : ci.parameters.githubRequester,
            };
            goal.provenance.push(prov);
            // Don't set approval for restart updates
            if (ci.parameters.state === types_1.SdmGoalState.approved) {
                goal.approval = prov;
                goal.approvalRequired = false;
            }
            else if (ci.parameters.state === types_1.SdmGoalState.pre_approved) {
                goal.preApproval = prov;
                goal.preApprovalRequired = false;
            }
            goal.state = ci.parameters.state;
            goal.ts = Date.now();
            goal.version = (goal.version || 0) + 1;
            delete goal.id;
            await storeGoals_1.storeGoal(ci.context, goal);
            return ci.context.messageClient.respond(messages_1.slackSuccessMessage("Set Goal State", `Successfully set state of ${slack_messages_1.italic(goal.name)} on ${slack_messages_1.codeLine(goal.sha.slice(0, 7))} of ${slack_messages_1.bold(`${goal.repo.owner}/${goal.repo.name}/${goal.branch}`)} to ${slack_messages_1.italic(ci.parameters.state)}`), { id: ci.parameters.msgId || string_1.guid() });
        },
    };
}
exports.updateGoalStateCommand = updateGoalStateCommand;
//# sourceMappingURL=updateGoal.js.map