"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TAG_PULL_REQUEST_BODY = void 0;
exports.getGerritRepoUrl = getGerritRepoUrl;
exports.mapPrStateToGerritFilter = mapPrStateToGerritFilter;
exports.mapGerritChangeToPr = mapGerritChangeToPr;
exports.mapGerritChangeStateToPrState = mapGerritChangeStateToPrState;
exports.extractSourceBranch = extractSourceBranch;
exports.findPullRequestBody = findPullRequestBody;
exports.mapBranchStatusToLabel = mapBranchStatusToLabel;
const tslib_1 = require("tslib");
const error_messages_1 = require("../../../constants/error-messages");
const logger_1 = require("../../../logger");
const hostRules = tslib_1.__importStar(require("../../../util/host-rules"));
const regex_1 = require("../../../util/regex");
const url_1 = require("../../../util/url");
const pr_body_1 = require("../pr-body");
exports.TAG_PULL_REQUEST_BODY = 'pull-request';
function getGerritRepoUrl(repository, endpoint) {
    // Find options for current host and determine Git endpoint
    const opts = hostRules.find({
        hostType: 'gerrit',
        url: endpoint,
    });
    const url = (0, url_1.parseUrl)(endpoint);
    if (!url) {
        throw new Error(error_messages_1.CONFIG_GIT_URL_UNAVAILABLE);
    }
    if (!(opts.username && opts.password)) {
        throw new Error('Init: You must configure a Gerrit Server username/password');
    }
    url.username = opts.username;
    url.password = opts.password;
    url.pathname = (0, url_1.joinUrlParts)(url.pathname, 'a', encodeURIComponent(repository));
    logger_1.logger.trace({ url: url.toString() }, 'using URL based on configured endpoint');
    return url.toString();
}
function mapPrStateToGerritFilter(state) {
    switch (state) {
        case 'closed':
            return 'status:closed';
        case 'merged':
            return 'status:merged';
        case '!open':
            return '-status:open';
        case 'open':
            return 'status:open';
        case 'all':
        default:
            return '-is:wip';
    }
}
function mapGerritChangeToPr(change) {
    return {
        number: change._number,
        state: mapGerritChangeStateToPrState(change.status),
        sourceBranch: extractSourceBranch(change) ?? change.branch,
        targetBranch: change.branch,
        title: change.subject,
        reviewers: change.reviewers?.REVIEWER?.filter((reviewer) => typeof reviewer.username === 'string').map((reviewer) => reviewer.username) ?? [],
        bodyStruct: {
            hash: (0, pr_body_1.hashBody)(findPullRequestBody(change)),
        },
    };
}
function mapGerritChangeStateToPrState(state) {
    switch (state) {
        case 'NEW':
            return 'open';
        case 'MERGED':
            return 'merged';
        case 'ABANDONED':
            return 'closed';
    }
    return 'all';
}
function extractSourceBranch(change) {
    let sourceBranch = undefined;
    if (change.current_revision) {
        const re = (0, regex_1.regEx)(/^Renovate-Branch: (.+)$/m);
        const message = change.revisions[change.current_revision]?.commit?.message;
        if (message) {
            sourceBranch = re.exec(message)?.[1];
        }
    }
    // for backwards compatibility
    if (!sourceBranch) {
        sourceBranch = change.hashtags
            ?.find((tag) => tag.startsWith('sourceBranch-'))
            ?.replace('sourceBranch-', '');
    }
    return sourceBranch ?? undefined;
}
function findPullRequestBody(change) {
    const msg = Array.from(change.messages ?? [])
        .reverse()
        .find((msg) => msg.tag === exports.TAG_PULL_REQUEST_BODY);
    if (msg) {
        return msg.message.replace(/^Patch Set \d+:\n\n/, ''); //TODO: check how to get rid of the auto-added prefix?
    }
    return undefined;
}
function mapBranchStatusToLabel(state, label) {
    const numbers = Object.keys(label.values).map((x) => parseInt(x, 10));
    switch (state) {
        case 'green':
            return Math.max(...numbers);
        case 'yellow':
        case 'red':
            return Math.min(...numbers);
    }
    // istanbul ignore next
    return label.default_value;
}
//# sourceMappingURL=utils.js.map