"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.ExecuteTaskListener = exports.executeTask = void 0;
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 redact_1 = require("@atomist/automation-client/lib/util/redact");
const createJob_1 = require("../../api-helper/misc/job/createJob");
const types_1 = require("../../typings/types");
const helpers_1 = require("./helpers");
/**
 * Execute an incoming job task event
 */
function executeTask(sdm) {
    return {
        name: "ExecuteTask",
        description: "Execute a job task",
        subscription: graphQL_1.subscription({
            name: "OnAnyJobTask",
            variables: {
                registration: sdm.configuration.name,
            },
        }),
        listener: exports.ExecuteTaskListener,
    };
}
exports.executeTask = executeTask;
const ExecuteTaskListener = async (e, ctx) => {
    const task = e.data.AtmJobTask[0];
    let jobData;
    let taskData;
    try {
        jobData = JSON.parse(task.job.data);
        taskData = JSON.parse(task.data);
    }
    catch (e) {
        logger_1.logger.warn("Parsing of job or task data failed: %s", e.message);
        await updateJobTaskState(task.id, types_1.AtmJobTaskState.failed, redact_1.redact(`Task command '${task.name}' failed: ${e.message}`), ctx);
    }
    if (taskData.type === createJob_1.JobTaskType.Command) {
        const md = globals_1.automationClientInstance().automationServer.automations.commands
            .find(c => c.name === task.name);
        if (!md) {
            await updateJobTaskState(task.id, types_1.AtmJobTaskState.failed, `Task command '${task.name}' could not be found`, ctx);
        }
        else {
            try {
                // Invoke the command
                const result = await globals_1.automationClientInstance().automationServer.invokeCommand(helpers_1.prepareCommandInvocation(md, taskData.parameters), helpers_1.prepareHandlerContext(ctx, jobData));
                // Handle result
                if (!!result && result.code !== undefined) {
                    if (result.code === 0) {
                        await updateJobTaskState(task.id, types_1.AtmJobTaskState.success, `Task command '${task.name}' successfully executed`, ctx);
                    }
                    else {
                        await updateJobTaskState(task.id, types_1.AtmJobTaskState.failed, redact_1.redact(result.message || `Task command '${task.name}' failed`), ctx);
                    }
                }
                else {
                    await updateJobTaskState(task.id, types_1.AtmJobTaskState.success, `Task command '${task.name}' successfully executed`, ctx);
                }
            }
            catch (e) {
                logger_1.logger.warn("Command execution failed: %s", e.message);
                await updateJobTaskState(task.id, types_1.AtmJobTaskState.failed, redact_1.redact(`Task command '${task.name}' failed: ${e.message}`), ctx);
            }
        }
    }
    return HandlerResult_1.Success;
};
exports.ExecuteTaskListener = ExecuteTaskListener;
/**
 * Update the job task status
 */
async function updateJobTaskState(id, state, message, ctx) {
    await ctx.graphClient.mutate({
        name: "SetJobTaskState",
        variables: {
            id,
            state: {
                state,
                message,
            },
        },
    });
}
//# sourceMappingURL=executeTask.js.map