var fs = require("fs");

var distDir = "./dist";

let fordel = (file, path, name) => {
  if (file.includes("_" + name)) {
    fs.unlink(path, err => {
      if (err) {
        console.error(err, `delete ${file} fail`);
        return;
      }
      console.log(file, "deleted");
    });
  }
};

var delOldFiles = function(name) {
  //打包时删除旧文件
  fs.readdir(distDir, function(err, files) {
    if (err) return console.log(err, "err");
    files.forEach(function(file) {
      if (file === "css" || file === "js") {
        fs.readdir(`${distDir}/${file}`, function(err, ifiles) {
          if (err) return console.log(err, "err");
          ifiles.forEach(function(ifile) {
            fordel(ifile,`${distDir}/${file}/${ifile}`,name)
          });
        });
      }
      fordel(file,`${distDir}/${file}`,name)
    });
  });
};

var getAllBuildFile = () => {
  //读取目录，排除目录中不需要的文件返回新的数组
  return new Promise((resolve, reject) => {
    fs.readdir("./src/pages", function(err, files) {
      if (err) {
        reject(err);
      }
      resolve(files.filter(fileName => fileName[0] !== "."));
    });
  });
};

module.exports = {
  delOldFiles: delOldFiles,
  getAllBuildFile: getAllBuildFile
};
