"use strict";
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());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
exports.__esModule = true;
exports.platformAddRemoteBundle = exports.platformUploadCfg = exports.platformUploadWeb = exports.platformBuildUpload = exports.PlatformBuild = void 0;
var common_1 = __importDefault(require("@hypgame/common"));
var child_process_1 = __importDefault(require("child_process"));
var fs_1 = __importDefault(require("fs"));
var path_1 = __importDefault(require("path"));
var FileUtil_1 = __importDefault(require("../util/FileUtil"));
var LogUtil_1 = __importDefault(require("../util/LogUtil"));
var PlatformBuildCfg_1 = require("./PlatformBuildCfg");
var PlatformBuildData_1 = __importDefault(require("./PlatformBuildData"));
var PlatformUpLoadTool_1 = __importDefault(require("./PlatformUpLoadTool"));
var AddRemoteBundleModule_1 = __importDefault(require("./module/AddRemoteBundleModule"));
var ImgCompressModule_1 = __importDefault(require("./module/ImgCompressModule"));
var PlatformFactory_1 = __importDefault(require("./platform/PlatformFactory"));
var PlatformBuild = /** @class */ (function () {
    function PlatformBuild() {
        this.buildGameData = new PlatformBuildData_1["default"]();
        this.curBuildPlatform = null;
        /** 构建配置数据 */
        this.buildGameData.buildCfgData = null;
        /** 当前平台构建配置数据 */
        this.buildGameData.platformCfg = null;
        /** 当前平台名字 */
        this.buildGameData.platformName = null;
        /** 游戏总配置 */
        this.buildGameData.appCfgData = null;
        /** 游戏版本配置 */
        this.buildGameData.appVersionCfg = null;
    }
    PlatformBuild.prototype.getJsonData = function (jsonPath) {
        var jsonStr = fs_1["default"].readFileSync(jsonPath, 'utf8');
        return JSON.parse(jsonStr);
    };
    /** 清除同名cmd窗口 */
    PlatformBuild.prototype.clearCmd = function () {
        var curCmdTitle = "YHBuild快速构建工具_" + this.buildGameData.platformName;
        var buildCmd = "";
        buildCmd = 'taskkill /FI  "WINDOWTITLE eq ' + curCmdTitle + '" /IM cmd.exe /F';
        child_process_1["default"].execSync(buildCmd, { stdio: [0, 1, 2] });
        buildCmd = "title " + curCmdTitle;
        child_process_1["default"].execSync(buildCmd, { stdio: [0, 1, 2] });
    };
    PlatformBuild.prototype.init = function (projectDir, channelName) {
        return __awaiter(this, void 0, void 0, function () {
            var platformName, platformBuild;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        console.log("===================== 快速构建游戏工具 YH =====================");
                        console.log("初始化工具配置...");
                        platformName = common_1["default"].curChannelData.platformType;
                        console.log("buildGameData projectDir, channelName, platformName...", projectDir, channelName, platformName);
                        return [4 /*yield*/, this.buildGameData.init(projectDir, channelName, platformName)];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this.initCosCmdTool()];
                    case 2:
                        _a.sent();
                        console.log("projectDir ===>", this.buildGameData.PROJECT_DIR);
                        /** 清除cmd */
                        this.clearCmd();
                        /** 记录时间 */
                        this.buildGameData.buildStartTime = new Date().getTime();
                        platformBuild = PlatformFactory_1["default"].Create(this.buildGameData.platformName);
                        return [4 /*yield*/, platformBuild.init(this.buildGameData)];
                    case 3:
                        _a.sent();
                        this.curBuildPlatform = platformBuild;
                        return [2 /*return*/];
                }
            });
        });
    };
    PlatformBuild.prototype.initCosCmdTool = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.checkPipInstalled()];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this.checkCosCmdInstalled()];
                    case 2:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    /** 检测python 安装 */
    PlatformBuild.prototype.checkPipInstalled = function () {
        return __awaiter(this, void 0, void 0, function () {
            var buildCmd, error_1, installExe;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        buildCmd = "";
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 2, , 7]);
                        buildCmd = "pip -V";
                        child_process_1["default"].execSync(buildCmd, { stdio: [0, 1, 2] });
                        return [3 /*break*/, 7];
                    case 2:
                        error_1 = _a.sent();
                        installExe = path_1["default"].join(this.buildGameData.PROJECT_DIR, "python-3.10.7-amd64.exe");
                        if (!fs_1["default"].existsSync(installExe)) return [3 /*break*/, 4];
                        console.log("等待安装中:", installExe);
                        return [4 /*yield*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
                                var _this = this;
                                return __generator(this, function (_a) {
                                    setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
                                        var flag;
                                        return __generator(this, function (_a) {
                                            switch (_a.label) {
                                                case 0: return [4 /*yield*/, this.checkPipInstalled()];
                                                case 1:
                                                    flag = _a.sent();
                                                    resolve(flag);
                                                    return [2 /*return*/];
                                            }
                                        });
                                    }); }, 2000);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 3: return [2 /*return*/, _a.sent()];
                    case 4:
                        buildCmd = " cd " + this.buildGameData.PROJECT_DIR + " && powershell Start-BitsTransfer -Source https://mirrors.huaweicloud.com/python/3.10.7/python-3.10.7-amd64.exe";
                        child_process_1["default"].execSync(buildCmd, { stdio: [0, 1, 2] });
                        buildCmd = " start " + installExe;
                        child_process_1["default"].execSync(buildCmd, { stdio: [0, 1, 2] });
                        return [4 /*yield*/, this.checkPipInstalled()];
                    case 5: return [2 /*return*/, _a.sent()];
                    case 6: return [3 /*break*/, 7];
                    case 7: return [2 /*return*/, true];
                }
            });
        });
    };
    /** 检测 coscmd 安装 */
    PlatformBuild.prototype.checkCosCmdInstalled = function () {
        return __awaiter(this, void 0, void 0, function () {
            var buildCmd, error_2, cosConfig;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        buildCmd = "";
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 2, , 4]);
                        buildCmd = "pip show coscmd";
                        child_process_1["default"].execSync(buildCmd, { stdio: [0, 1, 2] });
                        return [3 /*break*/, 4];
                    case 2:
                        error_2 = _a.sent();
                        buildCmd = "pip install coscmd";
                        child_process_1["default"].execSync(buildCmd, { stdio: [0, 1, 2] });
                        return [4 /*yield*/, LogUtil_1["default"].logInputObject({
                                secretId: "cos secretId",
                                secretKey: "cos secretKey",
                                Bucket: "cos Bucket",
                                Region: "cos Region"
                            })];
                    case 3:
                        cosConfig = _a.sent();
                        buildCmd = "coscmd config ";
                        buildCmd += " -a " + cosConfig.secretId;
                        buildCmd += " -s " + cosConfig.secretKey;
                        buildCmd += " -b " + cosConfig.Bucket;
                        buildCmd += " -r " + cosConfig.Region;
                        buildCmd += " -m 30";
                        child_process_1["default"].execSync(buildCmd, { stdio: [0, 1, 2] });
                        return [3 /*break*/, 4];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    PlatformBuild.prototype.buildPlatformGame = function () {
        return __awaiter(this, void 0, void 0, function () {
            var DebugMode, platformFolder, buildFolder, imgCompress;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        console.log("构建游戏渠道:", this.buildGameData.channelName);
                        console.log("构建游戏平台:", this.buildGameData.platformName);
                        console.log("构建游戏版本:", this.buildGameData.appVersionCfg.version);
                        DebugMode = this.buildGameData.appVersionCfg.DebugMode;
                        console.log("是否开启debug模式:", DebugMode);
                        this.updateRemoteUrl();
                        /** 构建工程 */
                        this.buildGame(DebugMode);
                        console.log("\u6784\u5EFA\u57FA\u7840\u7248\u672C\u65F6\u95F4:" + ((new Date().getTime() - this.buildGameData.buildStartTime) / 1000).toFixed(1) + "s ");
                        platformFolder = PlatformBuildCfg_1.PlatformFolder[this.buildGameData.platformName];
                        buildFolder = path_1["default"].join(this.buildGameData.PROJECT_DIR, "build", platformFolder);
                        imgCompress = new ImgCompressModule_1["default"]();
                        return [4 /*yield*/, imgCompress.init(buildFolder)];
                    case 1:
                        _a.sent();
                        console.log("\u6B64\u6B21\u6253\u5305\u5DF2\u82B1\u8D39:" + ((new Date().getTime() - this.buildGameData.buildStartTime) / 1000).toFixed(1) + "s ");
                        return [4 /*yield*/, this.curBuildPlatform.onBuildOver()];
                    case 2:
                        _a.sent();
                        this.onWorkOver();
                        return [2 /*return*/];
                }
            });
        });
    };
    /** 更新远程地址 */
    PlatformBuild.prototype.updateRemoteUrl = function () {
        var platformFolder = PlatformBuildCfg_1.PlatformFolder[this.buildGameData.platformName];
        var gameJsonPath = path_1["default"].join(this.buildGameData.PROJECT_DIR, "settings", platformFolder + ".json");
        if (!FileUtil_1["default"].isFileExist(gameJsonPath)) {
            console.log("平台打包配置表路径：", gameJsonPath);
            console.log("tips:为了初始化打包配置，尝试手动构建当前平台，再使用工具打包");
            LogUtil_1["default"].logError("平台打包配置表 错误请 检查");
            return;
        }
        var jsonStr = fs_1["default"].readFileSync(gameJsonPath, 'utf8');
        var jsonData = JSON.parse(jsonStr);
        jsonData["REMOTE_SERVER_ROOT"] = this.buildGameData.appCfgData.cdnRootUrl + "/" + this.buildGameData.resRemoteHost;
        jsonStr = JSON.stringify(jsonData);
        fs_1["default"].writeFileSync(gameJsonPath, jsonStr);
    };
    /** 编译基础工程 */
    PlatformBuild.prototype.buildGame = function (isDebug) {
        console.log("================ 开始自动构建 ================");
        var cocosExePath = this.buildGameData.buildCfgData.COCOS_IDE_PATH;
        var buildCmd = cocosExePath + " --path " + this.buildGameData.PROJECT_DIR + ' --build "platform=' + PlatformBuildCfg_1.PlatformCmd[this.buildGameData.platformName] + (isDebug ? ';debug=true;sourceMaps=true;' : '') + '"';
        try {
            child_process_1["default"].execSync(buildCmd, { stdio: [0, 1, 2] });
        }
        catch (error) {
            console.log(error);
            this.buildGame(isDebug);
        }
        console.log("================ 编译基础工程完成 ================");
    };
    PlatformBuild.prototype.uploadGameCfg = function () {
        return __awaiter(this, void 0, void 0, function () {
            var platformUpLoadTool;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        platformUpLoadTool = new PlatformUpLoadTool_1["default"](this.buildGameData);
                        return [4 /*yield*/, platformUpLoadTool.init(this.buildGameData.PROJECT_DIR, this.buildGameData.channelName, this.buildGameData.platformName)];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, platformUpLoadTool.getRefreshResultList()];
                    case 2:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    PlatformBuild.prototype.onWorkOver = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                console.log("构建游戏平台:", this.buildGameData.platformName);
                console.log("构建游戏渠道:", this.buildGameData.channelName);
                console.log("构建游戏版本:", this.buildGameData.appVersionCfg.version);
                console.log("\u6784\u5EFA\u65F6\u95F4:" + ((new Date().getTime() - this.buildGameData.buildStartTime) / 1000).toFixed(1) + "s ");
                console.log("===================== " + this.buildGameData.platformName + "[" + this.buildGameData.channelName + "] \u7248\u672C\u6784\u5EFA\u5B8C\u6210 YH =====================");
                LogUtil_1["default"].logInput("输入【Exit】退出打包工具", function (str) {
                    var flag = str.indexOf("Exit") != -1;
                    if (!flag) {
                        // console.log("url错误:", str)
                    }
                    return flag;
                });
                return [2 /*return*/];
            });
        });
    };
    return PlatformBuild;
}());
exports.PlatformBuild = PlatformBuild;
function platformBuildUpload(options) {
    return __awaiter(this, void 0, void 0, function () {
        var builder;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    builder = new PlatformBuild();
                    return [4 /*yield*/, builder.init(options.projectDir, options.channel)];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, builder.buildPlatformGame()];
                case 2:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
exports.platformBuildUpload = platformBuildUpload;
function platformUploadCfg(options) {
    return __awaiter(this, void 0, void 0, function () {
        var builder;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    builder = new PlatformBuild();
                    return [4 /*yield*/, builder.init(options.projectDir, options.channel)];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, builder.uploadGameCfg()];
                case 2:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
exports.platformUploadCfg = platformUploadCfg;
function platformUploadWeb(options) {
    return __awaiter(this, void 0, void 0, function () {
        var builder;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (options.platform != PlatformBuildCfg_1.Platform.h5) {
                        LogUtil_1["default"].logError("平台错误，默认平台为H5，当前平台为" + options.platform);
                        return [2 /*return*/];
                    }
                    builder = new PlatformBuild();
                    return [4 /*yield*/, builder.init(options.projectDir, options.channel)];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, builder.curBuildPlatform.onBuildOver()];
                case 2:
                    _a.sent();
                    return [4 /*yield*/, builder.onWorkOver()];
                case 3:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
exports.platformUploadWeb = platformUploadWeb;
/** 加载远程Bundle */
function platformAddRemoteBundle(options) {
    return __awaiter(this, void 0, void 0, function () {
        var platformName, builder, addRemoteBundleModule;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    platformName = common_1["default"].curChannelData.platformType;
                    if (platformName != PlatformBuildCfg_1.Platform.wx && platformName != PlatformBuildCfg_1.Platform.tt) {
                        LogUtil_1["default"].logError("平台错误，暂支持 WX 与 TT，当前平台为" + platformName);
                        return [2 /*return*/];
                    }
                    builder = new PlatformBuild();
                    return [4 /*yield*/, builder.init(options.projectDir, options.channel)];
                case 1:
                    _a.sent();
                    addRemoteBundleModule = new AddRemoteBundleModule_1["default"]();
                    return [4 /*yield*/, addRemoteBundleModule.init(builder.buildGameData)];
                case 2:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
exports.platformAddRemoteBundle = platformAddRemoteBundle;
