var fs = require("fs");

var iconv = require('iconv-lite');
var del = require('del');


var readPath = "./released/resource/";

//读取json文件
var data = iconv.decode(fs.readFileSync(readPath + "res.json"), "utf-8");//GBK
//反序列化
data = JSON.parse(data); //eval(data)
//取出里面的图片，暂存到tm文件夹中，同时删除文件夹里的，和本身json里的
if (!fs.existsSync("./released/tm"))
    fs.mkdirSync("./released/tm");
for (var i = 0; i < data.groups.length; i++) {
    var name = data.groups[i].name;
    var path = readPath + name + "/";
    var arr = data.groups[i].keys.split(",");
    //取出图片的，注意已排除jpg
    var images = arr.filter((f) => { return (f.substr(-4) == ".png" /*|| f.substr(-4) == ".jpg"*/) })
    //没有图片，
    if (!images.length) continue;
    //去掉原先数据里的
    // data.groups[i].keys = arr.filter((f) => { return (f.substr(-4) != ".png" && f.substr(-4) != ".jpg") }).join(",");
    //添加新的json，加到atlas里
    // if (data.groups[i].keys) data.groups[i].keys += ","
    data.groups[i].atlas = name + ".sht"
    //读取原先路径里的图片，写到tm的文件夹里，并删除原文件夹里的图片
    fs.mkdirSync("./released/tm/" + name);
    for (var m = 0; m < images.length; m++) {
        fs.writeFileSync(
            "./released/tm/" + name + "/" + images[m],
            fs.readFileSync(path + images[m])
        )
        del(path + images[m])
    }
}

//序列化
fs.writeFileSync(readPath + "res.json", JSON.stringify(data, "", "\t"));
