http           = require 'http'
fs             = require 'fs'
vows           = require 'vows'
assert         = require 'assert'
buffer         = require '../src/RequestBuffer'
{EventEmitter} = require 'events'

testStr        = "abcdefghijklmnopqrstuvwxyz0123456789"

# Server w/o and delays on event hooks
server1 = http.createServer (req, res) ->
  #Initialze the buffer
  req.buffer = new buffer req

  data = ''
  req.buffer.on 'data', (chunk) ->
    data += chunk

  req.buffer.on 'end', ->
    res.writeHead 200, {"Content-Type": "text/plain"}
    res.write data # Send the request data back as the response
    res.end()

  # Attach the listeners
  req.buffer.attach()
server1.listen 3000

# Server with a small delay before event hooks
server2 = http.createServer (req, res) ->
  #Initialze the buffer
  req.buffer = new buffer req

  # Late bind to the req events to simulate DB operations, etc
  setTimeout =>
    data = ''
    req.buffer.on 'data', (chunk) ->
      data += chunk

    req.buffer.on 'end', ->
      res.writeHead 200, {"Content-Type": "text/plain"}
      res.write data # Send the request data back as the response
      res.end()

    # Attach the listeners
    req.buffer.attach()
  , 200
server2.listen 3001

# test client
client = (server, promise, method = "POST") ->
  port = if server is 1 then 3000 else 3001
  http.request { host: "localhost", port: port, path: "/", method: method }, (res) =>
    data = ''
    res.on 'data', (chunk) =>
      data += chunk
    res.on 'end', =>
      promise.emit 'success', data

# Streamer to simulate network delays
streamer = (serverNo, delay = 0) ->
  promise = new EventEmitter
  req = client serverNo, promise
  chunks = testStr.match /.{3}/g
  
  writer = ->
    return req.end() unless chunks.length

    if delay > 0
      setTimeout ->
        req.write chunks.shift()
        writer()
      , delay
    else
      req.write chunks.shift()
      writer()
  writer()

  promise

vows
  .describe("Tests for RequestBuffer")
  .addBatch
    'A request with no async server and quick writes should':
      topic: ->
        streamer 1
      'render these 36 chars': (err, success) ->
        assert.equal success, testStr

    'A request with async server and quick writes should':
      topic: ->
        streamer 2
      'render these 36 chars': (err, success) ->
        assert.equal success, testStr

    'A request with no async server and slow writes should':
      topic: ->
        streamer 1, 100
      'render these 36 chars': (err, success) ->
        assert.equal success, testStr

    'A request with async server and slow writes should':
      topic: ->
        streamer 2, 100
      'render these 36 chars': (err, success) ->
        assert.equal success, testStr

    'A request with async server and slow writes and long delay should':
      topic: ->
        promise = new EventEmitter
        setTimeout  ->
          streamPromise = streamer 2, 100
          streamPromise.on 'success', (data) ->
            promise.emit 'success', data
        , 500

        promise
      'render these 36 chars': (err, success) ->
        assert.equal success, testStr
  .addBatch
    'Run teardown in this batch':
      'So here it is below': -> return # <- this is here because a topic is req'd
      teardown: -> 
        server1.close()
        server2.close()
  .export module