# The RequestBuffer. Stores request data until your application is ready to
# begin handling it.

{EventEmitter} = require('events')

module.exports = class RequestBuffer extends EventEmitter
  
  constructor: (req) ->
    # Only apply to POST PUT methods
    if req.method is 'POST' or req.method is 'PUT'

      @buffer   = []
      @attached = false # Set to true once we've indicated we're ready to handle the request events
      @ended    = false # Set to true when the HTTP request 'end' event is emitted

      req.on 'data', (chunk) =>
        if @attached
          @emit 'data', chunk
        else
          @buffer.push chunk
      
      req.on 'end', =>
        if @attached
          @emit 'end'
        @ended = true
   
  # We've set the listeners and are ready for the events   
  attach: ->
    # Let's drain the buffer first
    @emit 'data', chunk for chunk in @buffer
    @buffer = null # Empty the buffer just for giggles (and to free potentially sizeable amount of mem)

    # If the data's already done, emit here
    @emit 'end' if @ended

    # This will allow us to pick up the buffer now
    @attached = true
