
var fs = require("fs");
var exec = require('child_process').exec;
var iconv = require('iconv-lite');
var del = require('del');
const join = require('path').join;

// var packTextures = require("pack_textures")

//写入图集的文件夹
var outPath = "./released/resource/";
//读取散图的文件夹
var readPath = "./released/tm/";

var files = fs.readdirSync(readPath);
files.forEach(function (file) {
  //路径
  let fPath = join(readPath, file);
  //只处理文件夹
  if (fs.statSync(fPath).isDirectory()) {
    //判断文件夹内是否有图片
    if (!judgeHasImage(fPath)) return;

    //如果文件夹不存在
    if (!fs.existsSync(outPath + file)) {
      fs.mkdirSync(outPath + file);
    }
    else {
      //图集文件存在就删除
      if (fs.existsSync(outPath + file + "/" + file + ".json")) {
        del(outPath + file + "/" + file + ".json")
      }
      if (fs.existsSync(outPath + file + "/" + file + ".png")) {
        del(outPath + file + "/" + file + ".png")
      }
    }

    // packTextures(
    //   fPath,
    //   outPath + file + "/" + file,
    //   4096,
    //   4096,
    //   false,
    //   2,
    //   2,
    //   true,
    //   true
    // )
    //全局命令装过，就直接用命令行
    exec(
      'packTextures' + //基础指令
      ' -i ' + fPath +  //要合图集的文件夹路径
      ' -o ' + outPath + file + "/" + file +  //输出路径及名字
      ' --mw ' + 4096 + //最大宽度
      ' --mh ' + 4096 +//最大高度
      ' -p ' + false + //长宽是否2的指数，canvas下没必要，false
      ' --sp ' + 2 + //图片间隔
      ' --bp ' + 2 + //边界间隔
      ' -r ' + true + //是否允许图片旋转 
      ' -t ' + true  //是否允许裁切图片边缘透明像素
      , { encoding: 'utf8' }, (e) => {
        if (e) {
          console.log(e)
          return
        }
        console.log("生成图集：" + file)
      }
    )
  }
})

/**
 * 判断文件夹内是否有图片
 * @param {*} path 
 */
function judgeHasImage(path) {
  var files = fs.readdirSync(path);
  for (var i = 0; i < files.length; i++) {
    var itm = files[i]
    var stat = fs.statSync(path + "/" + itm);
    if (stat.isDirectory()) {
      //递归读取文件
      if (judgeHasImage(path + "/" + itm + "/")) return true;
    } else {
      if (itm.substr(-4) == ".jpg" || itm.substr(-4) == ".png") return true;
    }
  }
  return false;
}