 {EventEmitter}        = require 'events'
 {BufferedWriteStream} = require './buffered'
 
-# This is a Writable Stream.
-#
-# This is an EventEmitter with the following events:
+# A **ClientRequest** is returned when `Client.request()` is called.
+#
+# It is a Writable Stream and responds to the conventional
+# `write` and `end` methods.
+#
+# Its also an EventEmitter with the following events:
 #
 #   Event 'response'
 #   function (response) { }

    for key, value of metaVariables
      @env[key] = value

  write: (chunk) ->
    # Netstring encode the chunk and write it to the socket
    @bufferedSocket.write ns.nsWrite(chunk.toString())

  end: ->
    @bufferedSocket.end()

# This is a Readable Stream.
#
# This is an EventEmitter with the following events:
#
#   Event: `data`
#   function (chunk) { }

      # Catch and emit as a socket error
      @socket.emit 'error', error

# A **Client** establishes a connection to a worker process.
#
# It takes a `port` and `host` or a UNIX socket path.
#
# Its API is similar to `http.Client`.
#
#     var conn = client.createConnection('/tmp/nack.sock');
#     var request = conn.request('GET', '/', {'host', 'localhost'});
#     request.end();
#     request.on('response', function (response) {
#       console.log('STATUS: ' + response.statusCode);
#       console.log('HEADERS: ' + JSON.stringify(response.headers));
#       response.on('data', function (chunk) {
#         console.log('BODY: ' + chunk);
#       });
#     });
#
exports.Client = class Client extends Stream
  # Reconnect if the connection is closed.
  reconnect: ->
    if @readyState is 'closed'
      @connect @port, @host

  # Start the connection and create a ClientRequest.
  request: (args...) ->
    @reconnect()
    request = new ClientRequest @, args...
    request

  # Proxy a `http.ServerRequest` and `http.serverResponse` between
  # the `Client`.
  proxyRequest: (serverRequest, serverResponse) ->
    metaVariables =
      "REMOTE_ADDR": serverRequest.connection.remoteAddress
