"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.GoalExecutionRequestProcessor = exports.FilteringMetadataProcessor = exports.GoalExecutionAutomationEventListener = void 0;
const decorators_1 = require("@atomist/automation-client/lib/decorators");
const metadata_1 = require("@atomist/automation-client/lib/internal/metadata/metadata");
const metadataReading_1 = require("@atomist/automation-client/lib/internal/metadata/metadataReading");
const AbstractRequestProcessor_1 = require("@atomist/automation-client/lib/internal/transport/AbstractRequestProcessor");
const RequestProcessor_1 = require("@atomist/automation-client/lib/internal/transport/RequestProcessor");
const shutdown_1 = require("@atomist/automation-client/lib/internal/util/shutdown");
const string_1 = require("@atomist/automation-client/lib/internal/util/string");
const AutomationEventListener_1 = require("@atomist/automation-client/lib/server/AutomationEventListener");
const GraphClient_1 = require("@atomist/automation-client/lib/spi/graph/GraphClient");
const constructionUtils_1 = require("@atomist/automation-client/lib/util/constructionUtils");
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const cluster = require("cluster");
const _ = require("lodash");
const FulfillGoalOnRequested_1 = require("./FulfillGoalOnRequested");
class GoalExecutionAutomationEventListener extends AutomationEventListener_1.AutomationEventListenerSupport {
    constructor(sdm) {
        super();
        this.sdm = sdm;
    }
    async startupSuccessful(client) {
        if (cluster.isMaster) {
            const teamId = process.env.ATOMIST_GOAL_TEAM;
            const teamName = process.env.ATOMIST_GOAL_TEAM_NAME || teamId;
            const goalSetId = [process.env.ATOMIST_GOAL_SET_ID];
            const uniqueName = [process.env.ATOMIST_GOAL_UNIQUE_NAME];
            const correlationId = process.env.ATOMIST_CORRELATION_ID || string_1.guid();
            // Obtain goal via graphql query
            const agc = await Promise.resolve().then(() => require("@atomist/automation-client/lib/graph/ApolloGraphClient"));
            const graphClient = new agc.ApolloGraphClient(`${this.sdm.configuration.endpoints.graphql}/${teamId}`, { Authorization: `Bearer ${client.configuration.apiKey}` });
            const goal = await graphClient.query({
                name: "SdmGoalsByGoalSetIdAndUniqueName",
                variables: {
                    goalSetId,
                    uniqueName,
                },
                options: GraphClient_1.QueryNoCacheOptions,
            });
            // Create event and run event handler
            const event = {
                data: _.cloneDeep(goal),
                extensions: {
                    correlation_id: correlationId,
                    team_id: teamId,
                    team_name: teamName,
                    operationName: metadataReading_1.metadataFromInstance(new FulfillGoalOnRequested_1.FulfillGoalOnRequested(this.sdm.goalFulfillmentMapper, [...this.sdm.goalExecutionListeners])).name,
                },
                secrets: [{
                        uri: decorators_1.Secrets.OrgToken,
                        value: "null",
                    }],
            };
            try {
                await new Promise((resolve, reject) => {
                    client.processEvent(event, pResults => {
                        pResults.then(results => {
                            logger_1.logger.debug("Processing goal completed with results %j", results);
                            resolve();
                        }, reject);
                    });
                });
            }
            catch (e) {
                logger_1.logger.error(`Processing goal failed: ${e.message}`);
            }
            // Exit successfully to avoid job schedulers retrying.
            shutdown_1.safeExit(0);
        }
    }
}
exports.GoalExecutionAutomationEventListener = GoalExecutionAutomationEventListener;
class FilteringMetadataProcessor {
    constructor(allowedCommandHandlers, allowedEventHandlers) {
        this.allowedCommands = allowedCommandHandlers.map(h => metadataReading_1.metadataFromInstance(constructionUtils_1.toFactory(h)()).name);
        this.allowedEvents = allowedEventHandlers.map(h => metadataReading_1.metadataFromInstance(constructionUtils_1.toFactory(h)()).name);
    }
    process(metadata) {
        if (metadata_1.isEventHandlerMetadata(metadata) && !this.allowedEvents.includes(metadata.name)) {
            metadata.expose = false;
        }
        else if (metadata_1.isCommandHandlerMetadata(metadata) && !this.allowedCommands.includes(metadata.name)) {
            metadata.expose = false;
        }
        return metadata;
    }
}
exports.FilteringMetadataProcessor = FilteringMetadataProcessor;
class GoalExecutionRequestProcessor extends AbstractRequestProcessor_1.AbstractRequestProcessor {
    constructor(automations, configuration, listeners = []) {
        super(automations, configuration, listeners);
        this.automations = automations;
        this.configuration = configuration;
        this.listeners = listeners;
        this.graphClients = configuration.graphql.client.factory;
    }
    createGraphClient(event) {
        return this.graphClients.create(RequestProcessor_1.workspaceId(event), this.configuration);
    }
    createMessageClient(event, context) {
        return new NoOpMessageClient();
    }
    async sendStatusMessage(payload, ctx) {
        // Intentionally left empty
    }
}
exports.GoalExecutionRequestProcessor = GoalExecutionRequestProcessor;
class NoOpMessageClient {
    async delete(destinations, options) {
        logger_1.logger.debug(`Ignoring delete message '${JSON.stringify(options)}'`);
    }
    async respond(msg, options) {
        logger_1.logger.debug(`Ignoring respond message '${JSON.stringify(msg)}'`);
    }
    async send(msg, destinations, options) {
        logger_1.logger.debug(`Ignoring send message '${JSON.stringify(msg)}'`);
    }
}
//# sourceMappingURL=goalExecution.js.map