const fs = require("fs")

let arg = process.argv.splice(2);

if (!arg[0]) {
    console.error("未输入路径");
    return
}
var inUrl = arg[0];

var img = fs.readFileSync(inUrl + ".png")
var atlas = fs.readFileSync(inUrl + ".atlas")
// var json = fs.readFileSync(inUrl + ".json")
//为了能压缩格式化过的json
var json = Buffer.from(JSON.stringify(JSON.parse(fs.readFileSync(inUrl + ".json"))), "utf-8")

// console.log(img.byteLength)
// console.log(atlas.byteLength)
// console.log(json.byteLength)


//头部信息
var header = new ArrayBuffer(12);
var headerView = new DataView(header);//32位最高存储数值2^32-1，每个数值存储字节长度4
headerView.setUint32(0, img.byteLength, true);
headerView.setUint32(4, atlas.byteLength, true);
headerView.setUint32(8, json.byteLength, true);

fs.writeFileSync(inUrl + ".spi", Buffer.concat([
    toBuffer(header),
    img,
    atlas,
    json
], 12 + img.byteLength + atlas.byteLength + json.byteLength), { encoding: "binary" })


function string2buffer(str) {
    // 首先将字符串转为16进制
    let val = ""
    for (let i = 0; i < str.length; i++) {
        if (val === '') {
            val = str.charCodeAt(i).toString(16)
        } else {
            val += ',' + str.charCodeAt(i).toString(16)
        }
    }
    // 将16进制转化为ArrayBuffer
    return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
        return parseInt(h, 16)
    }))
}

function bytesToBinary(bytes) {
    const length = bytes.length;
    let result = '';
    for (let i = 0; i < length; i++) {
        const binStr = Number(bytes[i]).toString(2)
        result += '0'.repeat(8 - binStr.length) + binStr; // 不足八位前置补0
    }
    return result.toString();
}

function toBuffer(ab) {
    // var buf = new Buffer(ab.byteLength);
    var buf = Buffer.alloc(ab.byteLength);
    var view = new Uint8Array(ab);
    for (var i = 0; i < buf.length; ++i) {
        buf[i] = view[i];
    }
    return buf;
}
function toArrayBuffer(buf) {
    var ab = new ArrayBuffer(buf.length);
    var view = new Uint8Array(ab);
    for (var i = 0; i < buf.length; ++i) {
        view[i] = buf[i];
    }
    return ab;
}