// Require our core node modules.
var http = require( "http" );
var util = require( "util" );

// Require our core application modules.
var createContentStream = require( "./content-stream" ).createWriteStream;


// ----------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------- //


// Create a simple HTTP server so that we can aggregate incoming request content.
var httpServer = http.createServer(
	function handleHttpRequest( request, response ) {

		// Pipe the request into a ContentStream, which will aggregate the request
		// body and expose the content through a promise value.
		// --
		// NOTE: the ContentStream has a ".promise" property; but, as a convenience, it
		// also directly exposes ".then()", ".catch()", and ".finally()" methods which
		// are bound to the underlying promise.
		request
			.pipe( createContentStream() ) // <-- Returns stream, exposes .then().
			.on(
				"error",
				function handleErrorEvent( error ) {

					// NOTE: This is just here to demonstrate that I can listen for error
					// events directly on the stream (N possible events); or, I can use
					// the .catch() method (1 possible event); or, both.
					console.log( "Content error:", util.inspect( error ) );

				}
			)
			.then(
				function handleResolve( content ) {

					response.write( "CONTENT: " );
					response.write( content );
					response.write( "\n" );

				}
			)
			.catch(
				function handleReject( error ) {

					response.write( "ERROR: " );
					response.write( util.inspect( error ) );
					response.write( "\n" );

				}
			)
			.finally(
				function handleDone() {

					// No matter what happens, close the response.
					response.end( "Fin!" );

				}
			)
		;

	}
);

httpServer.listen( 8080 );

console.log( "Node server listening on port 8080." );