'use strict'

var extend = require('util')._extend
  , jsonSafeStringify = require('json-stringify-safe')
  , crypto = require('crypto')

function deferMethod() {
  if(typeof setImmediate === 'undefined') {
    return process.nextTick
  }

  return setImmediate
}

function constructObject(initialObject) {
  initialObject = initialObject || {}

  return {
    extend: function (object) {
      return constructObject(extend(initialObject, object))
    },
    done: function () {
      return initialObject
    }
  }
}

function constructOptionsFrom(uri, options) {
  var params = constructObject()
  if (typeof options === 'object') {
    params.extend(options).extend({uri: uri})
  } else if (typeof uri === 'string') {
    params.extend({uri: uri})
  } else {
    params.extend(uri)
  }
  return params.done()
}

function isFunction(value) {
  return typeof value === 'function'
}

function filterForCallback(values) {
  var callbacks = values.filter(isFunction)
  return callbacks[0]
}

function paramsHaveRequestBody(params) {
  return (
    params.options.body ||
    params.options.requestBodyStream ||
    (params.options.json && typeof params.options.json !== 'boolean') ||
    params.options.multipart
  )
}

function safeStringify (obj) {
  var ret
  try {
    ret = JSON.stringify(obj)
  } catch (e) {
    ret = jsonSafeStringify(obj)
  }
  return ret
}

function md5 (str) {
  return crypto.createHash('md5').update(str).digest('hex')
}

function isReadStream (rs) {
  return rs.readable && rs.path && rs.mode
}

function toBase64 (str) {
  return (new Buffer(str || '', 'utf8')).toString('base64')
}

exports.isFunction            = isFunction
exports.constructObject       = constructObject
exports.constructOptionsFrom  = constructOptionsFrom
exports.filterForCallback     = filterForCallback
exports.paramsHaveRequestBody = paramsHaveRequestBody
exports.safeStringify         = safeStringify
exports.md5                   = md5
exports.isReadStream          = isReadStream
exports.toBase64              = toBase64
exports.defer                 = deferMethod()
