'use strict'

var DEFAULT_STATUS_CODE = 200

function MockedResponse (res) {
  this.res = res
  this.cookies = {}
  this.headers = {}
  this.finished = false
  this.statusCode = DEFAULT_STATUS_CODE
}

MockedResponse.prototype.callbacks = {
  end: function () {}
}

MockedResponse.prototype.on = function (event, cb) {
  this.callbacks[event] = cb
}

MockedResponse.prototype.status = function (statusCode) {
  this.statusCode = parseInt(statusCode, 10)

  return this
}

MockedResponse.prototype.cookie = function (name, value, options) {
  this.cookies[name] = value

  if (this.res && typeof (this.res.setCookie) === 'function') {
    this.res.setCookie(name, value, options)
  }

  return this
}

MockedResponse.prototype.setHeader = function (name, value) {
  if (this.res) {
    this.res.header(name, value)
  }

  this.headers[name] = value

  return this
}

MockedResponse.prototype.setHeaders = function (headers) {
  this.headers = headers

  if (this.res && typeof (this.res.header) === 'function') {
    var that = this
    Object.keys(headers).forEach(function (header) {
      that.res.header(header, headers[header])
    })
  }

  return this
}

MockedResponse.prototype.send = function (maybeCode, maybeBody) {
  if (!this.finished) {
    var status = this.statusCode || 200
    var data

    if (typeof maybeCode === 'number') {
      status = maybeCode
      data = maybeBody
    } else {
      data = maybeCode
    }

    data = typeof (data) !== 'undefined' && data !== null ? data : ''

    if (data.toString) {
      // Check if the object passed has the "toString" method, if not, don't use it
      this.setHeader('Content-Length', data.toString().length)
    }

    this.finished = true

    if (this.res) {
      this.res.send(status, data)
    }

    var params = {
      status: status,
      body: data,
      headers: this.headers
    }

    // Only set cookies if status distinct than 40x or 50x
    if (status.toString().indexOf('4') !== 0 && status.toString().indexOf('5') !== 0) {
      params.cookies = this.cookies
    }

    this.callbacks.end(params)
  }
}

module.exports = MockedResponse

@@ -195,35 +195,14 @@
 ODE%0A
-%7D%0A%0AMockedResponse.prototype
+  this
 .cal
@@ -212,16 +212,18 @@
 cks = %7B%0A
+  
   end: f
@@ -236,16 +236,20 @@
 n () %7B%7D%0A
+  %7D%0A
 %7D%0A%0AMocke

The bad referenced object that causes bugs