"use strict";
/*
 * Copyright © 2019 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.slackReviewListenerRegistration = exports.slackReviewListener = void 0;
const HandlerResult_1 = require("@atomist/automation-client/lib/HandlerResult");
const MessageClient_1 = require("@atomist/automation-client/lib/spi/message/MessageClient");
const gitHub_1 = require("@atomist/automation-client/lib/util/gitHub");
const slack = require("@atomist/slack-messages");
/**
 * Route reviews to Slack in linked channels
 */
function slackReviewListener(opts = {}) {
    const paramsToUse = {
        pushReactionResponse: opts.pushReactionResponse,
        deepLink: opts.deepLink || gitHub_1.deepLink,
    };
    return async (ri) => {
        if (ri.review.comments.length > 0) {
            await sendReviewToSlack("Review comments", ri.review, ri.context, ri.addressChannels, paramsToUse.deepLink);
            return paramsToUse.pushReactionResponse;
        }
        return undefined;
    };
}
exports.slackReviewListener = slackReviewListener;
function slackReviewListenerRegistration(opts = {}) {
    return {
        name: "SlackReviewListener",
        listener: slackReviewListener(opts),
    };
}
exports.slackReviewListenerRegistration = slackReviewListenerRegistration;
async function sendReviewToSlack(title, pr, ctx, addressChannels, dl) {
    const mesg = {
        text: `*${title} on ${pr.repoId.owner}/${pr.repoId.repo}*`,
        attachments: pr.comments.map(c => reviewCommentToAttachment(pr.repoId, c, dl)),
    };
    await addressChannels(mesg);
    return HandlerResult_1.Success;
}
function reviewCommentToAttachment(grr, rc, dl) {
    const link = rc.sourceLocation ? slack.url(dl(grr, rc.sourceLocation), "jump to") :
        slack.url(grr.url + "/tree/" + grr.sha, "source");
    return {
        color: "#ff0000",
        author_name: rc.category,
        author_icon: "https://image.shutterstock.com/z/stock-vector-an-image-of-a-red-grunge-x-572409526.jpg",
        text: `${link} ${rc.detail}`,
        mrkdwn_in: ["text"],
        fallback: "error",
        actions: !!rc.fix ? [
            MessageClient_1.buttonForCommand({ text: "Fix" }, rc.fix.command, rc.fix.params),
        ] : [],
    };
}
//# sourceMappingURL=slackReviewListener.js.map