/****
 * 批量编译打包模板工具
 * 运行 npm run publish T_01 命令来打包T_01模板
 * 运行 npm run publish T_01,T_02,T_03,T_04  命令来分别打包 T_01,T_02,T_03,T_04 这四个模板，注意逗号要用英文的
 * 运行 npm run publish all 命令来打包所有模板
 */
  
const path = require("path");
const fs = require("fs");
const fsp = fs.promises;
const os = require('os');
const compressing = require("compressing");

//Linux系统上'Linux'
//macOS 系统上'Darwin' 
//Windows系统上'Windows_NT'
let sysType = os.type(); 

Date.prototype.Format = function(fmt) {
  var o = {
      "M+" : this.getMonth() + 1,
      "d+" : this.getDate(),
      "h+" : this.getHours(),
      "m+" : this.getMinutes(),
      "s+" : this.getSeconds(),
      "q+" : Math.floor((this.getMonth() + 3) / 3),
      "S" : this.getMilliseconds()
  };
  if (/(y+)/.test(fmt))
      fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
  if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

function clean(zipPath){
  if(fs.existsSync(zipPath)){
    fs.unlinkSync(zipPath);
  }
}

var copy=async function(src,dst){
  let paths = await fsp.readdir(src); //同步读取当前目录
  for(let i=0;i<paths.length;i++){
    let path = paths[i];
    var _src=src+'/'+path;
    var _dst=dst+'/'+path;
    var stats = await fsp.stat(_src);

    if(stats.isFile()){ //如果是个文件则拷贝 
      let readable=fs.createReadStream(_src);//创建读取流
      let writable=fs.createWriteStream(_dst);//创建写入流
      readable.pipe(writable);
    }else if(stats.isDirectory()){ //是目录则 递归 
      try {
        await fsp.access(_dst, fs.constants.F_OK);
      } catch (error) {
        fs.mkdirSync(_dst);
      } 
      await copy(_src,_dst);
    }
  } 
} 

const runSpawn = async function (){ 

  try {
    await fsp.access(path.resolve(__dirname,"../dist/form"), fs.constants.F_OK);
  } catch (error) {
    fs.mkdirSync(path.resolve(__dirname,"../dist/form"));
  } 
  try {
    await fsp.access(path.resolve(__dirname,"../dist/play"), fs.constants.F_OK);
  } catch (error) {
    fs.mkdirSync(path.resolve(__dirname,"../dist/play"));
  } 
  try {
    await fsp.access(path.resolve(__dirname,"../dist/lib"), fs.constants.F_OK);
  } catch (error) {
    fs.mkdirSync(path.resolve(__dirname,"../dist/lib"));
  } 
  await copy(path.resolve(__dirname,"../form"), path.resolve(__dirname,"../dist/form")); 
  await copy(path.resolve(__dirname,"../play"), path.resolve(__dirname,"../dist/play")); 
  await copy(path.resolve(__dirname,"../lib"), path.resolve(__dirname,"../dist/lib"));  

  let str = fs.readFileSync(path.resolve(__dirname,"../dist/play/index.html"),{encoding: 'utf8'});
  str = str.replace('<base href="">','<base href="template-base-href">'); 
  fs.writeFileSync(path.resolve(__dirname,"../dist/play/index.html"),str);

  await new Promise(function(resolve,reject){  
    let pkg = require("../package.json");  
    //要压缩的目录
    let zippath = path.resolve(__dirname,"../dist");  
    //压缩包的存放目录
    let date = new Date();
    let zipname = pkg.name+"_"+date.Format("yyyyMMdd hh-mm-ss");
    let zipdir = path.resolve(__dirname,"../publish/"+zipname+".zip");
    clean(zipdir); //删除原有的包
  
    const tarStream = new compressing.zip.Stream();
    fs.readdir(zippath,function(err,files){
      if(err){
        console.log("======文件打开异常======");
        console.log(err);
        reject();
      }
      for(let i=0;i<files.length;i++){
        tarStream.addEntry(zippath+"/"+files[i]);
      }
      let writeStream = fs.createWriteStream(zipdir);
      tarStream.pipe(writeStream); 
      writeStream.on('close', () => {
          console.log(`模板 ${pkg.name} 打包已完成！`);
          resolve();
      })
    });  

  }); 
}

// let projects = "";
// if(process.argv.length<3){
//   console.log("缺少参数");
//   return;
// }
// projects = process.argv[2];  

let exec = async function(){
  //压缩模板
  await runSpawn();
}

exec();  
 