'use strict';

var _stringify = require('babel-runtime/core-js/json/stringify');

var _stringify2 = _interopRequireDefault(_stringify);

require('source-map-support/register');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

process.on('unhandledRejection', function (reason, p) {
    console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
    // application specific logging, throwing an error, or other logic here
});

console.log('cold start');
require('source-map-support').install();
var json = require('format-json');
var consumer = require('sqs-consumer');
var githubUtils = require('../gtmGithubUtils.js');
var proxy = require('proxy-agent');
var AWS = require('aws-sdk');

AWS.config.update({ region: process.env.GTM_AWS_REGION });

function handle(event, context, callback) {
    /* eslint-disable */
    console.log('---------------------------------');
    console.log('Github-Results: ');
    console.log('---------------------------------');
    console.log('Payload', json.plain(event));
    /* eslint-enable */

    try {
        var _consumer = getQueue();

        _consumer.on('error', function (err) {
            console.log(err.message);
            throw err;
        });

        _consumer.on('empty', function () {
            console.log('results queue is empty.');
            _consumer.stop();
            var response = {
                statusCode: 200,
                body: (0, _stringify2.default)({
                    input: event
                })
            };
            return callback(null, response);
        });

        _consumer.start();
    } catch (e) {
        console.log(e.message);
        return callback(null, {
            statusCode: 401,
            headers: { 'Content-Type': 'text/plain' },
            body: e.message
        });
    }
}

function getQueue() {
    var awsOptions = {
        queueUrl: process.env.SQS_RESULTS_QUEUE_URL,
        waitTimeSeconds: 10,
        handleMessage: githubUtils.handleEventTaskResult
    };

    if (process.env.AWS_PROXY) {
        AWS.config.update({
            httpOptions: {
                agent: proxy(process.env.AWS_PROXY)
            }
        });
    }
    awsOptions.sqs = new AWS.SQS();

    return consumer.create(awsOptions);
}

module.exports = {
    handle: handle,
    getQueue: getQueue
};