"use strict";
var __assign = (this && this.__assign) || Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
            t[p] = s[p];
    }
    return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
var Logger = require("bunyan");
exports.Logger = Logger;
var cacheManager = require("cache-manager");
var context_1 = require("./context");
exports.Context = context_1.Context;
var github_app_1 = require("./github-app");
var logger_1 = require("./logger");
var resolver_1 = require("./resolver");
var robot_1 = require("./robot");
exports.Robot = robot_1.Robot;
var server_1 = require("./server");
var webhook_proxy_1 = require("./webhook-proxy");
var Webhooks = require('@octokit/webhooks');
var logRequestErrors = require('./middleware/log-request-errors');
var cache = cacheManager.caching({
    store: 'memory',
    ttl: 60 * 60 // 1 hour
});
var defaultApps = [
    require('./plugins/sentry'),
    require('./plugins/stats'),
    require('./plugins/default')
];
exports.createProbot = function (options) {
    options.webhookPath = options.webhookPath || '/';
    options.secret = options.secret || 'development';
    var webhook = new Webhooks({ path: options.webhookPath, secret: options.secret });
    var app = github_app_1.createApp({
        id: options.id,
        cert: options.cert
    });
    var server = server_1.createServer({ webhook: webhook.middleware, logger: logger_1.logger });
    function errorHandler(err) {
        switch (err.message) {
            case 'X-Hub-Signature does not match blob signature':
            case 'No X-Hub-Signature found on request':
                logger_1.logger.error('Go to https://github.com/settings/apps/YOUR_APP and verify that the Webhook secret matches the value of the WEBHOOK_SECRET environment variable.');
                break;
            case 'error:0906D06C:PEM routines:PEM_read_bio:no start line':
            case '{"message":"A JSON web token could not be decoded","documentation_url":"https://developer.github.com/v3"}':
                logger_1.logger.error('Your private key (usually a .pem file) is not correct. Go to https://github.com/settings/apps/YOUR_APP and generate a new PEM file. If you\'re deploying to Now, visit https://probot.github.io/docs/deployment/#now.');
                break;
            default:
                logger_1.logger.error(err);
        }
    }
    // Log all received webhooks
    webhook.on('*', function (event) {
        var webhookEvent = __assign({}, event, { event: event.name });
        delete webhookEvent.name;
        logger_1.logger.debug({ event: webhookEvent }, 'Webhook received');
        receive(webhookEvent);
    });
    // Log all webhook errors
    webhook.on('error', errorHandler);
    var robots = [];
    function receive(event) {
        return Promise.all(robots.map(function (robot) { return robot.receive(event); }));
    }
    function load(plugin) {
        if (typeof plugin === 'string') {
            plugin = resolver_1.resolve(plugin);
        }
        var robot = robot_1.createRobot({ app: app, cache: cache, catchErrors: true });
        // Connect the router from the robot to the server
        server.use(robot.router);
        // Initialize the plugin
        plugin(robot);
        robots.push(robot);
        return robot;
    }
    function setup(apps) {
        // Log all unhandled rejections
        process.on('unhandledRejection', errorHandler);
        // Load the given apps along with the default apps
        apps.concat(defaultApps).forEach(function (app) { return load(app); });
        // Register error handler as the last middleware
        server.use(logRequestErrors);
    }
    return {
        server: server,
        webhook: webhook,
        receive: receive,
        logger: logger_1.logger,
        load: load,
        setup: setup,
        start: function () {
            if (options.webhookProxy) {
                webhook_proxy_1.createWebhookProxy({
                    url: options.webhookProxy,
                    port: options.port,
                    path: options.webhookPath,
                    logger: logger_1.logger
                });
            }
            server.listen(options.port);
            logger_1.logger.info('Listening on http://localhost:' + options.port);
        }
    };
};
module.exports.createRobot = robot_1.createRobot;
//# sourceMappingURL=index.js.map