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

const { packTextures } = require("texture-packer-hycv");

//写入图集的文件夹
const outPath = path.resolve("./released/resource/") + "/";

//读取散图的文件夹
const readPath = path.resolve("./released/tm/");

const 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) {
	const files = fs.readdirSync(path);
	for (let i = 0; i < files.length; i++) {
		const itm = files[i];
		const 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;
}
