/**
 * flushRes.js
 * Created by 还有醋v on 2022/9/19 下午6:10.
 * Copyright © 2022 haiyoucuv. All rights reserved.
 */

//生成res.json

//遍历资源文件夹，生成
const fs = require('fs');
const path = require("path");

function flushRes(pathOrigin = ".") {

	const readPath = "./resource/"
	const files = fs.readdirSync(readPath);
	const obj = { groups: [] };//每项包括keys合name

	files.forEach(function (file) {
		//路径
		let fPath = path.join(readPath, file);
		//只处理文件夹
		if (fs.statSync(fPath).isDirectory()) {
			//继续读每个子文件夹，json和png名字有相同的，只留json，
			let sonFiles = fs.readdirSync(fPath);
			//没有文件
			if (!sonFiles.length) return;
			//取出所有json
			const jsons = sonFiles.filter((f) => {
				return f.substr(-5) === ".json";
			});
			//去掉json所带png的图片
			sonFiles = sonFiles.filter((f) => {
				return jsons.indexOf(f.substring(0, f.length - 4) + ".json") === -1
			});
			//去掉mac上的缓存文件
			sonFiles = sonFiles.filter((f) => {
				return f !== '.DS_Store'
			});
			const group = {
				keys: "", name: file,
			};
			for (let i = 0; i < sonFiles.length; i++) {
				if (i !== 0) group.keys += ",";
				group.keys += sonFiles[i];
			}
			obj.groups.push(group);
		}
	})

	obj.path = "./resource/";

	const writeStr = JSON.stringify(obj, "", "\t");
	//生成json
	fs.writeFileSync(readPath + "res.json", writeStr);
	//TS也更新
	const endPath = './src/';
	const endFile = `export const ResJson = ${writeStr.replace(
		`"path": "./resource/"`,
		`"path": "${pathOrigin}/resource/"`
	)}`;
	fs.writeFileSync(endPath + "ResJson.ts", endFile);

	console.log("资源更新完成");
}

flushRes();

exports.flushRes = flushRes;

