'use strict';

const AWS = require('aws-sdk');
const sns = new AWS.SNS({
    region: process.env.AWS_REGION
});

// There is no warning state in cloudwatch
const STATUS = {
    "OK": 0,
    "ALARM": 2,
    "INSUFFICIENT_DATA": 3
};

// Map AWS account to environment
const ENVIRONMENT = {
    "544854064936": "cpe-master",
    "994136867826": "cpe-tools",
    "857171411193": "twilight-production",
    "157787312516": "twilight-test",
    "001591884629": "twilight-shadow",
    "795085625652": "voip-production",
    "797929491177": "curse-production"
};

const REGION = {
    "US West (Oregon)": "pdx",
};

exports.handler = (event, context, callback) => {
    var promises = [];
    for (var i = 0; i < event.Records.length; i++) {
        console.log('Parsing message id', i);
        promises.push(translateToSensu(JSON.parse(event.Records[i].Sns.Message)));
    }

    Promise.all(promises).then(() => {
        callback(null, 'Added ' + promises.length + ' elements to sensu sns topic');
});
};

var translateToSensu = (message) => {
    var envOrAccount = ENVIRONMENT[message.AWSAccountId] || message.AWSAccountId;

    var data = {
        "client": message.AlarmName + "-" + REGION[message.Region],
        "check": {
            "status": STATUS[message.NewStateValue],
            "name": message.AlarmName,
            "awsAccountId": message.AWSAccountId,
            "source": envOrAccount + "-" + REGION[message.Region],
            "issued": message.StateChangeTime,
            "executed": message.StateChangeTime,
            "output": message.NewStateReason,
            "environment": envOrAccount,
            "trigger": message.Trigger,
            "timestamp": Date.new
        }
    };

    var params = {
        Message: JSON.stringify(data),
        TopicArn: 'arn:aws:sns:' + process.env.AWS_REGION + ':' + message.AWSAccountId + ':sensu_ingress',
        MessageAttributes: {
            pipe: {
                DataType: "String",
                StringValue: "results"
            },
            type: {
                DataType: "String",
                StringValue: "direct"
            }
        }
    };

    return sns.publish(params).promise();

};