'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.Event = undefined;

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

var _stringify2 = _interopRequireDefault(_stringify);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

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

require('babel-polyfill');

var _crypto = require('crypto');

var _crypto2 = _interopRequireDefault(_crypto);

var _AgentLogger = require('./AgentLogger');

var _AgentLogger2 = _interopRequireDefault(_AgentLogger);

var _Agent = require('./Agent');

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

var log = _AgentLogger2.default.log();

/**
 * representation of an event generated from a github hook SQS message
 */

var Event = exports.Event = function () {
    function Event(message) {
        (0, _classCallCheck3.default)(this, Event);

        this.attrs = Event.validateMessage(message);
        this.payload = Event.prepareEventPayload(message, this.attrs);
        this.log = log.child({ ghEventId: this.attrs.ghEventId });
        _Agent.Agent.systemConfig.event.current = this.payload;
    }

    /**
     * list of required message attributes on SQS messages
     * @returns {[string,string,string,string,string]}
     */


    (0, _createClass3.default)(Event, null, [{
        key: 'validateMessage',


        /**
         * verify message attributes exist and check signing
         * @param message
         * @returns {{}} result attribute object
         */
        value: function validateMessage(message) {
            var result = {};

            Event.requiredAttributes.forEach(function (attr) {
                try {
                    result[attr] = message.MessageAttributes[attr].StringValue;
                } catch (TypeError) {
                    throw new Error('No Message Attribute \'' + attr + '\' in Message - discarding Event!');
                }
            });

            if (!Event.checkEventSignature(result.ghEventSignature, message)) {
                throw new Error('Event signature mismatch - discarding Event!');
            } else {
                log.info('Event signature verified. processing event..');
            }

            return result;
        }

        /**
         * sign the event message, and check that github signature matches
         * @param signature
         * @param message
         * @returns {boolean}
         */

    }, {
        key: 'checkEventSignature',
        value: function checkEventSignature(signature, message) {
            var checkEvent = Event.buildCheckObject(message);
            log.debug('eventString for signature check: ' + (0, _stringify2.default)(checkEvent));

            var calculatedSig = 'sha1=' + _crypto2.default.createHmac('sha1', process.env.GTM_GITHUB_WEBHOOK_SECRET).update((0, _stringify2.default)(checkEvent), 'utf-8').digest('hex');

            if (calculatedSig !== signature) {
                throw new Error('signature mismatch: ' + calculatedSig + ' !== ' + signature);
            }

            return calculatedSig === signature;
        }
    }, {
        key: 'buildCheckObject',
        value: function buildCheckObject(message) {
            return {
                id: message.MessageAttributes.ghEventId.StringValue,
                body: message.Body,
                messageAttributes: {
                    ghEventId: {
                        DataType: 'String',
                        StringValue: message.MessageAttributes.ghEventId.StringValue
                    },
                    ghEventType: {
                        DataType: 'String',
                        StringValue: message.MessageAttributes.ghEventType.StringValue
                    },
                    ghTaskConfig: {
                        DataType: 'String',
                        StringValue: message.MessageAttributes.ghTaskConfig.StringValue
                    },
                    ghAgentGroup: {
                        DataType: 'String',
                        StringValue: message.MessageAttributes.ghAgentGroup.StringValue
                    }
                }
            };
        }

        /**
         * create eventData object from message body, and attach message attributes
         * @param message
         * @param attrs
         */

    }, {
        key: 'prepareEventPayload',
        value: function prepareEventPayload(message, attrs) {
            var payload = JSON.parse(message.Body);
            payload.ghEventId = attrs.ghEventId;
            payload.ghEventType = attrs.ghEventType;
            payload.ghTaskConfig = JSON.parse(attrs.ghTaskConfig);
            payload.ghAgentGroup = attrs.ghAgentGroup;
            payload.ghEventSignature = attrs.ghEventSignature;
            payload.MessageHandle = message.ReceiptHandle;

            return payload;
        }
    }, {
        key: 'requiredAttributes',
        get: function get() {
            return ['ghEventId', 'ghEventType', 'ghAgentGroup', 'ghTaskConfig', 'ghEventSignature'];
        }
    }]);
    return Event;
}();