var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
const path = require("path");
const fs = require("fs");
const AutoUpload = require("./upload");
const compressAllImage = require("./minImg");
const { exec } = require("child_process");
const obfuscator = require("./obfuscator");
let buildVersion = 0;
function getRemotePath() {
    return `/db_games/ccc_game/template/${buildVersion}/`;
}
function getRemoteUrl() {
    // return `https://yun.duiba.com.cn${getRemotePath()}`;
    return `//yun.duiba.com.cn${getRemotePath()}`;
}
function getGitInfo(path) {
    return new Promise((resolve) => {
        let gitStr = '';
        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);
        });
    });
}
/**
 * 开始打包
 * @param options
 * @param callback
 */
function onBuildStart(options, callback) {
    if (options.platform !== "web-mobile")
        return;
    buildVersion = Date.now();
    callback();
}
/**
 * 打包结束之前
 * @param options
 * @param callback
 */
function onBeforeBuildFinish(options, callback) {
    return __awaiter(this, void 0, void 0, function* () {
        if (options.platform !== "web-mobile")
            return;
        const remoteUrl = getRemoteUrl();
        // 非调试模式下开启变态代码防调试
        if (!options.debug) {
            Editor.success("兑吧发布插件 >> 变态代码防调试");
            const mainIndexPath = path.join(options.dest, "assets/main/index.js");
            const obCode = yield obfuscator(mainIndexPath);
            // fs.writeFileSync(mainIndexPath, obCode);
            Editor.success("兑吧发布插件 >> 变态代码防调试成功");
        }
        else {
            Editor.warn("兑吧发布插件 >> 已开启调试模式，请确保不是上线代码");
            Editor.warn("兑吧发布插件 >> 已开启调试模式，请确保不是上线代码");
            Editor.warn("兑吧发布插件 >> 已开启调试模式，请确保不是上线代码");
            Editor.Dialog.messageBox({ message: "兑吧发布插件\n已开启调试模式\n请确保不是上线代码" });
        }
        Editor.success("兑吧发布插件 >> 开始修改脚本");
        // main.js 所在路径
        const mainJsPath = path.join(options.dest, "main.js");
        // 读取 main.js
        let script = fs.readFileSync(mainJsPath, "utf8");
        const gitInfo = yield getGitInfo(options.project);
        // 添加一点脚本
        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;
        // 保存
        fs.writeFileSync(mainJsPath, script);
        Editor.success("兑吧发布插件 >> 修改脚本完成");
        Editor.success("兑吧发布插件 >> 开始压缩图片");
        yield compressAllImage(options);
        Editor.success("兑吧发布插件 >> 压缩图片结束");
        callback();
    });
}
/**
 * 打包完成
 * @param options
 * @param callback
 */
function onBuildFinish(options, callback) {
    return __awaiter(this, void 0, void 0, function* () {
        if (options.platform !== "web-mobile")
            return;
        const remoteUrl = getRemoteUrl();
        Editor.success("兑吧发布插件 >> 开始生成皮肤模版");
        const htmlPath = path.join(options.dest, "index.html");
        const indexHtml = fs.readFileSync(htmlPath, "utf8")
            .replace(/{{__remoteUrl__}}/g, remoteUrl);
        fs.writeFileSync(htmlPath, indexHtml);
        Editor.success("兑吧发布插件 >> 生成皮肤模版完成");
        Editor.success("兑吧发布插件 >> 打包完成，开始上传");
        const dir = path.join(Editor.Project.path, "build/web-mobile");
        const autoUpload = new AutoUpload({
            dir: dir,
            originDir: getRemotePath(),
        });
        yield autoUpload.start();
        Editor.success("兑吧发布插件 >> 上传完成");
        Editor.success("兑吧发布插件 >> 版本号:" + buildVersion);
        Editor.Dialog.messageBox({ message: "兑吧发布插件\n上传完成\n可以发布" });
        callback();
    });
}
module.exports = {
    load() {
        Editor.Builder.on("build-start", onBuildStart);
        Editor.Builder.on("before-change-files", onBeforeBuildFinish);
        Editor.Builder.on("build-finished", onBuildFinish);
    },
    unload() {
        Editor.Builder.removeListener("build-start", onBuildStart);
        Editor.Builder.removeListener("before-change-files", onBeforeBuildFinish);
        Editor.Builder.removeListener("build-finished", onBuildFinish);
    },
    messages: {
        "duiba-publish:test": function (event, question) {
            // const dir = path.resolve(Editor.Project.path, "build/web-mobile");
            //
            // const autoUpload = new AutoUpload({
            // 	dir: dir,
            // 	originDir: `/db_games/cocosTest/${Date.now()}/`
            // });
            //
            // autoUpload.start();
            // const tempDir = Editor.url("packages://duiba-publish/index.html");
            // let indexHtml = fs.readFileSync(tempDir, "utf8");
            // indexHtml = indexHtml.replace(/{{__remoteUrl__}}/g, "1231231");
            // fs.writeFileSync(path.join(Editor.Project.path, "build-templates/web-mobile/index1.html"), indexHtml);
        }
    }
};
