"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.sumSdmGoalEvents = exports.fetchGoalsForCommit = exports.fetchCommitForSdmGoal = exports.findSdmGoalOnCommit = exports.fetchGoalsFromPush = void 0;
const configuration_1 = require("@atomist/automation-client/lib/configuration");
const GraphClient_1 = require("@atomist/automation-client/lib/spi/graph/GraphClient");
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const stringify = require("json-stringify-safe");
const _ = require("lodash");
const sdmGoal_1 = require("./sdmGoal");
const storeGoals_1 = require("./storeGoals");
function fetchGoalsFromPush(sdmGoal) {
    if (sdmGoal.push && sdmGoal.push.goals) {
        const goals = _.cloneDeep(sumSdmGoalEvents(sdmGoal.push.goals.filter(g => g.goalSetId === sdmGoal.goalSetId)));
        const push = _.cloneDeep(sdmGoal.push);
        delete push.goals;
        goals.forEach(g => g.push = push);
        return goals;
    }
    return [];
}
exports.fetchGoalsFromPush = fetchGoalsFromPush;
async function findSdmGoalOnCommit(ctx, id, providerId, goal) {
    const sdmGoals = await fetchGoalsForCommit(ctx, id, providerId);
    const matches = sdmGoals.filter(g => storeGoals_1.goalCorrespondsToSdmGoal(goal, g));
    if (matches && matches.length > 1) {
        logger_1.logger.warn("More than one match found for %s/%s; they are %j", goal.environment, goal.name, matches);
    }
    if (matches.length === 0) {
        logger_1.logger.debug("Did not find goal %s on commit %s#%s", sdmGoal_1.goalKeyString(goal), id.repo, id.sha);
        return undefined;
    }
    return matches[0];
}
exports.findSdmGoalOnCommit = findSdmGoalOnCommit;
async function fetchCommitForSdmGoal(ctx, goal) {
    const variables = { sha: goal.sha, repo: goal.repo.name, owner: goal.repo.owner, branch: goal.branch };
    const result = await ctx.graphClient.query({
        name: "CommitForSdmGoal",
        variables: { sha: goal.sha, repo: goal.repo.name, owner: goal.repo.owner, branch: goal.branch },
        options: Object.assign(Object.assign({}, GraphClient_1.QueryNoCacheOptions), { log: configuration_1.configurationValue("sdm.query.logging", false) }),
    });
    if (!result || !result.Commit || result.Commit.length === 0) {
        throw new Error("No commit found for goal " + stringify(variables));
    }
    return result.Commit[0];
}
exports.fetchCommitForSdmGoal = fetchCommitForSdmGoal;
async function fetchGoalsForCommit(ctx, id, providerId, goalSetId) {
    const result = [];
    const size = 200;
    let offset = 0;
    const query = sdmGoalOffsetQuery(id, goalSetId, providerId, ctx);
    let pageResult = await query(offset, size);
    while (pageResult && pageResult.SdmGoal && pageResult.SdmGoal.length > 0) {
        result.push(...pageResult.SdmGoal);
        offset += size;
        pageResult = await query(offset, size);
    }
    if (!result) {
        throw new Error(`No result finding goals for commit ${providerId}/${id.owner}/${id.repo}#${id.sha} on ${id.branch}`);
    }
    if (result.length === 0) {
        logger_1.logger.warn("0 goals found for commit %j, provider %s", id, providerId);
    }
    if (result.some(g => !g)) {
        logger_1.logger.warn("Null or undefined goal found for commit %j, provider %s", id, providerId);
    }
    // only maintain latest version of SdmGoals from the current goal set
    const goals = sumSdmGoalEvents(result);
    // query for the push and add it in
    if (goals.length > 0) {
        const push = await ctx.graphClient.query({
            name: "PushForSdmGoal",
            variables: {
                owner: id.owner,
                repo: id.repo,
                providerId,
                branch: goals[0].branch,
                sha: goals[0].sha,
            },
            options: {
                log: configuration_1.configurationValue("sdm.query.logging", false),
            },
        });
        return goals.map(g => {
            const goal = _.cloneDeep(g);
            goal.push = push.Commit[0].pushes[0];
            return goal;
        });
    }
    return goals;
}
exports.fetchGoalsForCommit = fetchGoalsForCommit;
function sumSdmGoalEvents(some) {
    // For some reason this won't compile with the obvious fix
    // tslint:disable-next-line:no-unnecessary-callback-wrapper
    const byKey = _.groupBy(some, sg => `${sg.goalSetId}-${sdmGoal_1.goalKeyString(sg)}`);
    const summedGoals = Object.keys(byKey).map(k => sumEventsForOneSdmGoal(byKey[k]));
    return summedGoals;
}
exports.sumSdmGoalEvents = sumSdmGoalEvents;
function sumEventsForOneSdmGoal(events) {
    if (events.length === 1) {
        return events[0];
    }
    // SUCCESS OVERRIDES ALL
    const success = events.find(e => e.state === "success");
    return success || _.maxBy(events, e => e.ts);
}
function sdmGoalOffsetQuery(id, goalSetId, providerId, ctx) {
    return async (offset, size) => {
        return ctx.graphClient.query({
            name: "SdmGoalsForCommit",
            variables: {
                owner: id.owner,
                repo: id.repo,
                branch: id.branch,
                sha: id.sha,
                providerId,
                goalSetId,
                qty: size,
                offset,
            },
            options: Object.assign(Object.assign({}, GraphClient_1.QueryNoCacheOptions), { log: configuration_1.configurationValue("sdm.query.logging", false) }),
        });
    };
}
//# sourceMappingURL=fetchGoalsOnCommit.js.map