/**
 * Created by nuintun on 2015/4/27.
 */

'use strict';

var fs = require('fs');
var File = require('vinyl');
var through = require('through2');
var util = require('../util');
var transport = require('./transport');
var debug = require('debug')('transport:include');

function include(options){
  return through.obj(function (file, enc, callback){
    if (file.isNull()) {
      // return empty file
      callback(null, file);
    }

    if (file.isStream()) {
      return callback(util.throwError('streaming not supported.'));
    }

    var self = this;
    var cwd = file.cwd;
    var base = file.base;
    var endFile = file.clone();
    var files = getFiles(file, options);

    endFile.contents = null;

    // file dependency
    files.forEach(function (path){
      var f = createFile(path, cwd, base);

      debug('filepath:%s dependency', f.path);
      self.push(f);
    });

    // file self
    debug('filepath: %s self', file.path);
    this.push(file);
    // end file
    debug('filepath: %s end', endFile.path);
    this.push(endFile);

    callback();
  });
}

function getFiles(file, options){
  var pkg = file.package;
  var include = options.include;

  if (Array.isArray(pkg.localDepsMaps)) {
    return pkg.localDepsMaps.filter(function (meta){
      if (options.ignore.indexOf(meta.path)) {
        return false;
      }

      switch (include) {
        case 'all':
          return true;
        case 'self':
          return false;
          break;
        case 'relative':
        default :
          return util.isRelative(meta.id);
      }
    });
  }

  return [];
}

function createFile(path, cwd, base, options){
  return through.obj(function (file, enc, callback){
    this.push(new File({
      cwd: cwd,
      base: base,
      path: path,
      contents: fs.readFileSync(path)
    }));

    callback();
  }).pipe(transport(options));
}

module.exports = include;
@@ -558,58 +558,8 @@
 is;%0A
-    var cwd = file.cwd;%0A    var base = file.base;%0A
     
@@ -590,23 +590,12 @@
 ();%0A
+%0A
    
- var files =
  get
@@ -597,32 +597,38 @@
   getFiles(file,
+ this,
  options);%0A%0A    
@@ -657,186 +657,8 @@
 l;%0A%0A
-    // file dependency%0A    files.forEach(function (path)%7B%0A      var f = createFile(path, cwd, base);%0A%0A      debug('filepath:%25s dependency', f.path);%0A      self.push(f);%0A    %7D);%0A%0A
     
@@ -868,16 +868,24 @@
 es(file,
+ stream,
  options
@@ -887,16 +887,62 @@
 tions)%7B%0A
+  var cwd = file.cwd;%0A  var base = file.base;%0A
   var pk
@@ -1039,22 +1039,27 @@
 ) %7B%0A    
-return
+var files =
  pkg.loc
@@ -1407,25 +1407,135 @@
 %7D);%0A
+%0A
   
-%7D%0A%0A  return %5B%5D;
+  // file dependency%0A    files.forEach(function (path)%7B%0A      createFile(path, cwd, base, options).pipe(stream);%0A    %7D);%0A  %7D
 %0A%7D%0A%0A

add source file