
module.exports = HTTPDuplex

var util = require('util')
  , http = require('http')
  , https = require('https')
  , stream = require('stream')

util.inherits(HTTPDuplex, stream.Duplex)


function HTTPDuplex (protocol) {
  stream.Duplex.call(this)

  this._req = null
  this._res = null
  this._client = null

  if (protocol === 'https:') {
    this._client = https
  }
  else if (protocol === 'http:') {
    this._client = http
  }
}

HTTPDuplex.prototype.start = function (options) {
  var self = this

  self._req = self._client.request(options)

  self._req.on('response', function (res) {

    self._res = res
    self.emit('response', res)

    res.on('data', function (chunk) {
      if (!self.push(chunk)) {
        self._res.pause()
      }
    })

    res.on('end', function () {
      self.push(null)
    })
  })
}

HTTPDuplex.prototype._read = function (n) {
  if (this._res) {
    this._res.resume()
  }
}

HTTPDuplex.prototype._write = function (chunk, encoding, cb) {
  return this._req.write(chunk, encoding, cb)
}

HTTPDuplex.prototype.end = function (chunk, encoding, cb) {
  return this._req.end(chunk, encoding, cb)
}


module.exports = HTTPDuplex

var util = require('util')
  , http = require('http')
  , https = require('https')
  , stream = require('stream')

util.inherits(HTTPDuplex, stream.Duplex)


function HTTPDuplex (protocol) {
  stream.Duplex.call(this)

  this._req = null
  this._res = null
  this._client = null

  if (protocol === 'https:') {
    this._client = https
  }
  else if (protocol === 'http:') {
    this._client = http
  }
}

HTTPDuplex.prototype.start = function (options) {
  var self = this

  self._req = self._client.request(options)

  self._req.on('response', function (res) {

    self._res = res
    self.emit('response', res)

    self._res.on('data', function (chunk) {
      if (!self.push(chunk)) {
        self._res.pause()
      }
    })

    self._res.on('end', function () {
      self.push(null)
    })
  })
}

HTTPDuplex.prototype._read = function (n) {
  if (this._res) {
    this._res.resume()
  }
}

HTTPDuplex.prototype._write = function (chunk, encoding, cb) {
  return this._req.write(chunk, encoding, cb)
}

HTTPDuplex.prototype.end = function (chunk, encoding, cb) {
  return this._req.end(chunk, encoding, cb)
}

Allow piping in the response event
Allow piping in the response event
