var fs = require('fs');
var path = require('path');

function copyFile(srcPath, tarPath, cb) {
  var rs = fs.createReadStream(srcPath);
  rs.on('error', function (err) {
    if (err) {
      console.log('read error', srcPath);
    }
    if (cb) {
      cb(err);
    }
  });
  var ws = fs.createWriteStream(tarPath);
  ws.on('error', function (err) {
    if (err) {
      console.log('write error', tarPath);
    }
    if (cb) {
      cb(err);
    }
  });
  ws.on('close', function (ex) {
    if (cb) {
      cb(ex);
    }
  });
  rs.pipe(ws);
}

function copyFolder(srcDir, tarDir, cb) {
  fs.readdir(srcDir, function (err, files) {
    var count = 0;
    var checkEnd = function () {
      if (++count === files.length && cb) {
        cb();
      }
    };
    if (err) {
      checkEnd();
      return;
    }

    files.forEach(function (file) {
      var srcPath = path.join(srcDir, file);
      var tarPath = path.join(tarDir, file);

      fs.stat(srcPath, function (err, stats) {
        if (stats.isDirectory()) {
          fs.mkdir(tarPath, function (err) {
            if (err) {
              return;
            }

            copyFolder(srcPath, tarPath, checkEnd);
          });
        } else {
          copyFile(srcPath, tarPath, checkEnd);
        }
      });
    });

    //为空时直接回调
    if (files.length === 0 && cb) {
      cb();
    }
  });
}

function someFolderLength(list, projectFolder) {
  return list.filter((name) => {
    const fileName = path.resolve(process.cwd(), path.join('.', name));
    const isDir = fs.statSync(fileName).isDirectory();
    return name.indexOf(projectFolder) !== -1 && isDir;
  }).length
}

function validateFolder(folder) {
  try {
    const stat = fs.statSync(path.join(process.cwd(),`${folder}`))
    if(stat.isDirectory()) {
      return '存在相同文件夹，请重新输入！'
    }
  } catch (error) {
    return true
  }
}

module.exports = {
  copyFolder: copyFolder,
  someFolderLength:someFolderLength,
  validateFolder: validateFolder
};

