"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.onAfterMake = exports.onBeforeMake = exports.onError = exports.unload = exports.onAfterBuild = exports.onAfterCompressSettings = exports.onBeforeCompressSettings = exports.onBeforeBuild = exports.load = exports.throwError = void 0;
const fs = __importStar(require("fs"));
const child_process_1 = require("child_process");
const upload_1 = __importDefault(require("./upload"));
const obfuscator_1 = require("./obfuscator");
const minImg_1 = require("./minImg");
const PACKAGE_NAME = 'duiba-publish';
let allAssets = [];
exports.throwError = true;
const load = async function () {
    console.log(`[${PACKAGE_NAME}] Load cocos plugin example in builder.`);
    allAssets = await Editor.Message.request('asset-db', 'query-assets');
};
exports.load = load;
let buildVersion = 0;
function getRemotePath(uploadDir = 'template3d') {
    return `/db_games/ccc_game/${uploadDir}/${buildVersion}/`;
}
function getRemoteUrl(uploadDir = 'template3d') {
    // return `https://yun.duiba.com.cn${getRemotePath(uploadDir)}`;
    return `//yun.duiba.com.cn${getRemotePath(uploadDir)}`;
}
function getGitInfo(path) {
    return new Promise((resolve) => {
        let gitStr = '';
        (0, child_process_1.exec)(`cd ${path} && git remote -v && git branch --show-current & git config --global user.name`, (_err, stdout, _stderr) => {
            if (stdout)
                gitStr += encodeURIComponent(stdout.replace(/\n/g, ';'));
            resolve(gitStr);
        });
    });
}
const onBeforeBuild = async function (options, result) {
    if (options.platform !== "web-mobile")
        return;
    buildVersion = Date.now();
};
exports.onBeforeBuild = onBeforeBuild;
const onBeforeCompressSettings = async function (options, result) {
    if (options.platform !== "web-mobile")
        return;
    const remoteUrl = getRemoteUrl(options.packages[PACKAGE_NAME].uploadDir);
    result.settings.assets.server = remoteUrl;
    result.settings.plugins.jsList = [];
    // result.settings.plugins.jsList = result.settings.plugins.jsList.map((jsUrl) => {
    //    return `${remoteUrl}src/${jsUrl}`;
    // });
};
exports.onBeforeCompressSettings = onBeforeCompressSettings;
const onAfterCompressSettings = async function (options, result) {
    // Todo some thing
    console.log('webTestOption', 'onAfterCompressSettings');
};
exports.onAfterCompressSettings = onAfterCompressSettings;
const onAfterBuild = async function (options, result) {
    if (options.platform !== "web-mobile")
        return;
    const remoteUrl = getRemoteUrl(options.packages[PACKAGE_NAME].uploadDir);
    /*************************** 防调试 ***************************/
    // 非调试模式下开启变态代码防调试
    if (!options.debug) {
        console.log("%c兑吧发布插件 >> 变态代码防调试", "color: green");
        if (fs.existsSync(result.dest + "/remote")) {
            fs.readdirSync(result.dest + "/remote")
                .forEach((dirName) => {
                (0, obfuscator_1.obfuscate)(result.dest + "/remote/" + dirName + "/index.js");
            });
        }
        if (fs.existsSync(result.dest + "/assets")) {
            fs.readdirSync(result.dest + "/assets")
                .forEach((dirName) => {
                (0, obfuscator_1.obfuscate)(result.dest + "/assets/" + dirName + "/index.js");
            });
        }
        if (fs.existsSync(result.dest + "/src/chunks")) {
            fs.readdirSync(result.dest + "/src/chunks")
                .forEach((fileName) => {
                (0, obfuscator_1.obfuscate)(result.dest + "/src/chunks/" + fileName);
            });
        }
        console.log("%c兑吧发布插件 >> 变态代码防调试成功", "color: green");
    }
    else {
        console.warn("兑吧发布插件 >> 已开启调试模式，请确保不是上线代码");
        console.warn("兑吧发布插件 >> 已开启调试模式，请确保不是上线代码");
        console.warn("兑吧发布插件 >> 已开启调试模式，请确保不是上线代码");
        await Editor.Dialog.warn("兑吧发布插件\n已开启调试模式\n请确保不是上线代码");
    }
    /*************************** 防调试 ***************************/
    /*************************** 修改脚本 ***************************/
    console.log("%c兑吧发布插件 >> 开始修改脚本", "color: green");
    // application.js 所在路径
    const mainJsPath = result.dest + "/application.js";
    // 读取 application.js
    let script = fs.readFileSync(mainJsPath, "utf8");
    const gitInfo = await getGitInfo(result.dest);
    // 添加一点脚本
    script = `window.__remoteUrl__ = \"${remoteUrl}\";\n`
        + `window.__remoteAssets__ = window.__remoteUrl__ + \"assets/\";\n`
        + `window.__version__ = ${buildVersion};\n`
        + `window.__ENV__ = "prod";\n`
        + `window.___G___ = "${gitInfo}";\n\n\n`
        + script;
    script = script.replace("src/settings.json", `${remoteUrl}src/settings.json`);
    // 保存
    fs.writeFileSync(mainJsPath, script);
    console.log("%c兑吧发布插件 >> 修改脚本完成", "color: green");
    /*************************** 修改脚本 ***************************/
    /*************************** 压缩图片 ***************************/
    console.log("%c兑吧发布插件 >> 开始压缩图片", "color: green");
    await (0, minImg_1.compressAllImage)(["assets", "remote"], result.dest);
    console.log("%c兑吧发布插件 >> 压缩图片结束", "color: green");
    /*************************** 压缩图片 ***************************/
    /*************************** 生成皮肤模版 ***************************/
    console.log("%c兑吧发布插件 >> 开始生成皮肤模版", "color: green");
    const htmlPath = result.dest + "/index.html";
    const indexHtml = fs.readFileSync(htmlPath, "utf8")
        .replace(/{{__remoteUrl__}}/g, remoteUrl);
    fs.writeFileSync(htmlPath, indexHtml);
    console.log("%c兑吧发布插件 >> 生成皮肤模版完成", "color: green");
    /*************************** 生成皮肤模版 ***************************/
    /*************************** 打包完成，开始上传 ***************************/
    console.log("%c兑吧发布插件 >> 打包完成，开始上传", "color: green");
    const autoUpload = new upload_1.default({
        dir: result.dest,
        originDir: getRemotePath(options.packages[PACKAGE_NAME].uploadDir),
    });
    await autoUpload.start();
    console.log("%c兑吧发布插件 >> 上传完成", "color: green");
    /*************************** 打包完成，开始上传 ***************************/
    console.log("%c兑吧发布插件 >> 版本号:" + buildVersion, "color: green");
    await Editor.Dialog.info("兑吧发布插件\n上传完成\n可以发布");
};
exports.onAfterBuild = onAfterBuild;
const unload = async function () {
    console.log(`[${PACKAGE_NAME}] Unload cocos plugin example in builder.`);
};
exports.unload = unload;
const onError = async function (options, result) {
    // Todo some thing
    console.warn(`${PACKAGE_NAME} run onError`);
};
exports.onError = onError;
const onBeforeMake = async function (root, options) {
    console.log(`onBeforeMake: root: ${root}, options: ${options}`);
};
exports.onBeforeMake = onBeforeMake;
const onAfterMake = async function (root, options) {
    console.log(`onAfterMake: root: ${root}, options: ${options}`);
};
exports.onAfterMake = onAfterMake;
