/**
 * Created by nuintun on 2016/6/24.
 */

'use strict';

const http = require('http');
const FileSend = require('./index');
const colors = require('colors/safe');
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;

var first = true;

function createServer(root, port){
  http.createServer(function (request, response){
    var send = new FileSend(request, {
      root: root || './',
      maxAge: '3day',
      ignore: ['/**/.*?(/*.*|/)'],
      index: ['pets', 'name.txt']
    });

    if (first) {
      first = !first;

      console.log('--------------------------------------------------------------------');
    }

    console.log('ROOT:', colors.red.bold(send.root));
    console.log('URL:', colors.green.bold(send.url));
    console.log('PATH:', colors.yellow.bold(send.path));
    console.log('REALPATH:', colors.cyan.bold(send.realpath));
    console.log('QUERY:', colors.green.bold(JSON.stringify(send.query, null, 2)));

    send
      .pipe(response)
      .on('headers', function (){
        console.log('HEADERS:', colors.magenta.bold(JSON.stringify(send.headers, null, 2)));
        console.log('--------------------------------------------------------------------');
      });
  }).listen(port || 8080, '127.0.0.1');
}

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork().on('listening', function (address){
      // Worker is listening
      console.log(colors.green.bold('Server run at port:'), colors.cyan.bold(address.port));
    });
  }
} else {
  // Workers can share any TCP connection
  // In this case it is an HTTP server
  createServer();
  createServer('./test/fixtures', 9091);
}

@@ -345,16 +345,38 @@
 ponse)%7B%0A
+    var last = false;%0A
     var 
@@ -406,16 +406,16 @@
 uest, %7B%0A
-
       ro
@@ -978,24 +978,196 @@
 ull, 2)));%0A%0A
+    function always()%7B%0A      if (!last) %7B%0A        last = true;%0A%0A        console.log('--------------------------------------------------------------------');%0A      %7D%0A    %7D%0A%0A
     send%0A   
@@ -1324,100 +1324,77 @@
     
-console.log('--------------------------------------------------------------------');%0A      %7D
+always();%0A      %7D)%0A      .on('end', always)%0A      .on('close', always
 );%0A 
@@ -1550,16 +1550,44 @@
 tening',
+ (function (i)%7B%0A      return
  functio
@@ -1599,16 +1599,18 @@
 dress)%7B%0A
+  
       //
@@ -1632,24 +1632,26 @@
 ening%0A      
+ 
+ 
 console.log(
@@ -1675,16 +1675,33 @@
 ('Server
+ thread ' + i + '
  run at 
@@ -1746,17 +1746,30 @@
 ));%0A    
-%7D
+  %7D;%0A    %7D(i))
 );%0A  %7D%0A%7D
@@ -1857,16 +1857,16 @@
  server%0A
+
   create
@@ -1879,47 +1879,6 @@
 ();%0A
-  createServer('./test/fixtures', 9091);%0A
 %7D%0A

update files