nUtil = require 'util'
request = require 'request'
conf = require '../config'
async = require 'async'

exports.log = (obj) ->
  console.log nUtil.inspect obj, {colors: true, depth: 10}

exports.sendToSlackImmediate = (msg, channel, cb) ->
  if typeof channel == 'function'
    cb = channel
    channel = undefined
  processSlackMessage msg, channel, cb

exports.sendToSlack = (msg, channel, cb) ->
  if typeof channel == 'function'
    cb = channel
    channel = undefined
  slackMsgQueue.push {msg, channel}, (err) ->
    cb?(err)

# Renders a tokenized string.
exports.replacePlaceholders = (str, context) ->
  for key, value of context
    re = new RegExp("\\[#{key}\\]", 'gi')
    value = '' unless value?
    str = str.replace re, value
  return str

# We create a slack message queue to ensure all slack
# messages are delivered in-order.
slackMsgQueue = async.queue (task, qCb) ->
  msg = task.msg
  channel = task.channel || null
  processSlackMessage msg, channel, (err) ->
    qCb err

processSlackMessage = (msg, channel, cb) ->
  return cb() unless url = conf.get 'slackUrl'
  payload =
    username: 'Mold'
    icon_emoji: ':docker:'
    text: msg
  payload.channel = channel if channel
  request.post
    url: url
    json: payload
    (err, response, body) ->
      cb(err)
