"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PackageScript = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const xxtea_node_1 = __importDefault(require("xxtea-node"));
const pako_1 = __importDefault(require("pako"));
const FileUtils_1 = __importDefault(require("../utils/FileUtils"));
const SCRIPT_PACKAGE = fs_1.default.readFileSync(path_1.default.join(__dirname, '..', '..', 'template', 'SCRIPT_PACKAGE.js')).toString();
const SETTING_GOURPLIST_REGEXP = /groupList:\s*(\[['",a-zA-Z0-9\s]+])/mg;
const SETTING_COLLISIONMATRIX_REGEXP = /collisionMatrix:\s*(\[[\[\],truefalse\s]+\])/mg;
function PackageScript(key, buildPath, isolate = false, xxtea, ungzip = false) {
    const bundleDir = path_1.default.join(buildPath, 'assets', key);
    if (fs_1.default.existsSync(path_1.default.join(bundleDir, 'config.subgame.json'))) {
        console.warn(`Package [${key}] script packaged`);
        return;
    }
    console.log(`Package [${key}] find config`);
    const configPath = FileUtils_1.default.find(bundleDir, /config\.([a-zA-Z0-9\.]+\.)?json/);
    fs_1.default.renameSync(configPath, path_1.default.join(bundleDir, 'config.subgame.json'));
    console.log(`Package [${key}] config finded, renames`);
    console.log(`Package [${key}] find index script`);
    const scriptPath = FileUtils_1.default.find(bundleDir, /index\.([a-zA-Z0-9\.]+\.)?js/);
    const scriptEncrypt = path_1.default.extname(scriptPath) === '.jsc';
    let scriptBuffer = fs_1.default.readFileSync(scriptPath);
    let script;
    if (scriptEncrypt) {
        script = decryptJSC(scriptBuffer, xxtea, ungzip);
        console.log(`Package [${key}] index script decrypt result: ${script.substring(0, 100)}...`);
    }
    else {
        script = scriptBuffer.toString();
    }
    if (isolate) {
        console.log(`Package [${key}] find settings`);
        const settingPath = FileUtils_1.default.find(path_1.default.join(buildPath, 'src'), /settings\.([a-zA-Z0-9\.]+\.)?js/);
        const settingsBuffer = fs_1.default.readFileSync(settingPath);
        let settings;
        if (path_1.default.extname(settingPath) === '.jsc') {
            settings = decryptJSC(settingsBuffer, xxtea, ungzip);
            console.log(`Package [${key}] settings script decrypt result: ${settings.substring(0, 100)}...`);
        }
        else
            settings = settingsBuffer.toString();
        const groupList = SETTING_GOURPLIST_REGEXP.exec(settings)[1];
        const collisionMatrix = SETTING_COLLISIONMATRIX_REGEXP.exec(settings)[1];
        console.log(`Package [${key}] settings finded, saved`);
        script = SCRIPT_PACKAGE
            .replace('"%{subgame_key}"', key)
            .replace('"%{subgame_content}"', script)
            .replace('"%{subgame_group_list}"', groupList)
            .replace('"%{subgame_collision_matrix}"', collisionMatrix);
        console.log(`Package [${key}] class isolate`);
    }
    if (scriptEncrypt)
        fs_1.default.writeFileSync(scriptPath, encryptJS(script, xxtea, ungzip));
    else
        fs_1.default.writeFileSync(scriptPath, script);
    fs_1.default.renameSync(scriptPath, path_1.default.join(bundleDir, 'index.subgame' + path_1.default.extname(scriptPath)));
    console.log(`Package [${key}] index script packaged`);
}
exports.PackageScript = PackageScript;
const decryptJSC = (data, key, ungzip = true) => {
    let res = xxtea_node_1.default.decrypt(data, xxtea_node_1.default.toBytes(key));
    res = pako_1.default.ungzip(res);
    return xxtea_node_1.default.toString(res);
};
const encryptJS = (data, key, ungzip = true) => {
    const res = pako_1.default.gzip(xxtea_node_1.default.toBytes(data), { level: 6 });
    const result = xxtea_node_1.default.encrypt(res, xxtea_node_1.default.toBytes(key));
    console.dir(result);
    return result;
};
