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

//写入图集的文件夹,将文件夹内所有的json合并，并删除原先json
var readPath = "./released/resource/";

//读取json文件
var data = iconv.decode(fs.readFileSync(readPath + "res.json"), "utf-8");//GBK
//反序列化
data = JSON.parse(data);
var files = fs.readdirSync(readPath);
// let obj = {};
let count = 0;
let countAll = files.length
files.forEach(function (file) {
    //路径
    let fPath = join(readPath, file);
    //只处理文件夹
    if (fs.statSync(fPath).isDirectory()) {
        //读文件夹fPath里的json文件
        fs.readdir(fPath, function (err, files) {
            if (err) {
                console.warn(err)
            } else {
                var hasJson
                //遍历
                for (var i = 0; i < files.length; i++) {
                    let filename = files[i];
                    if (filename.indexOf(".json") == -1) continue
                    hasJson = true;
                    //获取当前文件的绝对路径
                    let filedir = path.join(fPath, filename);
                    let content = fs.readFileSync(filedir, 'utf-8');
                    let group = getGroupByName(filename.replace(".json", ""), data.groups)
                    group.atlas = JSON.parse(content);
                    //删除原先json
                    del(filedir)
                    if (++count == countAll) endFun();
                }
                if(!hasJson)if (++count == countAll) endFun();
                //序列化，不格式化，节省内存
            }
        })
    } else {
        if (++count == countAll) endFun();
    }
})

function endFun() {
    console.log("资源配置js生成完毕")
    // del(join(readPath, "res.json"))
    fs.writeFileSync(readPath + "res.json", JSON.stringify(data, "", "\t"));
}

function getGroupByName(name, groups) {
    var group;
    for (var i = 0; i < groups.length; i++) {
        if (groups[i].name === name) {
            group = groups[i];
            break;
        }
    }
    return group
}
