/*

slack-notify
https://github.com/andrewchilds/slack-notify

*/

var exec = require('child_process').exec;
var request = require('request');
var _ = require('lodash');

module.exports = function (url) {
  var pub = {};

  pub.request = function (data, done) {
    if (!url) {
      console.log('No Slack URL configured.');
      return false;
    }

    if (!done) {
      done = function(){};
    }

    request.post(url, {
      form: {
        payload: JSON.stringify(data)
      }
    }, function(err, response) {
      if (err) {
        return done(err);
      }
      if (response.body != 'ok') {
        return done(new Error(response.body));
      }

      done();
    });
  };

  pub.send = function (options, done) {
    if (_.isString(options)) {
      options = { text: options };
    }

    // Merge options with defaults
    var defaults = {
      channel: '#general',
      username: 'Robot',
      text: '',
      icon_emoji: ':bell:'
    };
    var data = _.assign(defaults, options);

    // Move the fields into attachments
    if (options.fields) {
      if (!data.attachments) {
        data.attachments = [];
      }

      data.attachments.push({
        fallback: 'Alert details',
        fields: _.map(options.fields, function (value, title) {
          return {
            title: title,
            value: value,
            short: (value + '').length < 25
          };
        })
      });

      delete(data.fields);
    }

    // Remove the default icon_emoji if icon_url was set in options. Otherwise the default emoji will always override the url
    if (options.icon_url && !options.icon_emoji) {
      delete(data.icon_emoji);
    }

    pub.request(data, done);
  };

  pub.extend = function (defaults) {
    return function (options, done) {
      if (_.isString(options)) {
        options = { text: options };
      }

      pub.send(_.extend(defaults, options), done);
    };
  };

  pub.bug = pub.extend({
    channel: '#bugs',
    icon_emoji: ':bomb:',
    username: 'Bug'
  });

  pub.alert = pub.extend({
    channel: '#alerts',
    icon_emoji: ':warning:',
    username: 'Alert'
  });

  pub.note = pub.extend({
    channel: '#alerts',
    icon_emoji: ':bulb:',
    username: 'Note'
  });

  pub.success = pub.extend({
    channel: '#alerts',
    icon_emoji: ':trophy:',
    username: 'Hoorah'
  });

  return pub;
};

@@ -64,50 +64,8 @@
 */%0A%0A
-var exec = require('child_process').exec;%0A
 var 

Clean up slack-notify.js