"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 __spreadArrays = (this && this.__spreadArrays) || function () {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
exports.__esModule = true;
var path_1 = __importDefault(require("path"));
var fs_1 = __importDefault(require("fs"));
var request_1 = __importDefault(require("request"));
var FileUtil_1 = __importDefault(require("../../util/FileUtil"));
var PlatformBuildCfg_1 = require("../PlatformBuildCfg");
/** 跨项目加载bundle模块 */
var AddRemoteBundleModule = /** @class */ (function () {
    function AddRemoteBundleModule() {
        this.buildGameData = null;
        this.remoteBundleCfg = null;
    }
    /** 编译WX工程 */
    AddRemoteBundleModule.prototype.init = function (buildGameData) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.buildGameData = buildGameData;
                        return [4 /*yield*/, this.initRemoteBundleLoader()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    /** 初始化 */
    AddRemoteBundleModule.prototype.initRemoteBundleLoader = function () {
        return __awaiter(this, void 0, void 0, function () {
            var PROJECT_DIR, cfgJsonPath, jsonStr, remoteBundleLib, _a, _b, _i, key;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        PROJECT_DIR = this.buildGameData.PROJECT_DIR;
                        cfgJsonPath = path_1["default"].join(PROJECT_DIR, "assets", "remoteBundleCfg.json");
                        if (!fs_1["default"].existsSync(cfgJsonPath)) {
                            console.warn("remoteBundleCfg 文件不存在!");
                            return [2 /*return*/];
                        }
                        console.log("------------------ 添加 远程Bundle 加载依赖 ----------------");
                        jsonStr = fs_1["default"].readFileSync(cfgJsonPath, 'utf8');
                        this.remoteBundleCfg = JSON.parse(jsonStr);
                        remoteBundleLib = this.remoteBundleCfg.remoteBundleLib;
                        _a = [];
                        for (_b in remoteBundleLib)
                            _a.push(_b);
                        _i = 0;
                        _c.label = 1;
                    case 1:
                        if (!(_i < _a.length)) return [3 /*break*/, 4];
                        key = _a[_i];
                        return [4 /*yield*/, this.updateProjectByBundleLib(key)];
                    case 2:
                        _c.sent();
                        _c.label = 3;
                    case 3:
                        _i++;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**根据 bundle库 更新项目  */
    AddRemoteBundleModule.prototype.updateProjectByBundleLib = function (bundleLibName) {
        return __awaiter(this, void 0, void 0, function () {
            var bundleLibUrl, bundleLibCfgUrl, bundleLibCfg, version, targetBundleLibUrl, bundleLibVersionCfgUrl, bundleLibVersionCfg, dependencies, bundleVersions, allBundles, dependLibBundles, srcBundles, i, curSrcBundleName, version_1;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        console.log("处理版本库内容:", bundleLibName);
                        bundleLibUrl = this.remoteBundleCfg.libRootUrl + "/" + bundleLibName;
                        bundleLibCfgUrl = bundleLibUrl + "/bundleLibCfg.json";
                        return [4 /*yield*/, this.getRemoteJson(bundleLibCfgUrl)];
                    case 1:
                        bundleLibCfg = _a.sent();
                        version = bundleLibCfg.version;
                        targetBundleLibUrl = bundleLibUrl + "/libVersion/" + version;
                        bundleLibVersionCfgUrl = targetBundleLibUrl + "/bundleLibVersionCfg.json";
                        return [4 /*yield*/, this.getRemoteJson(bundleLibVersionCfgUrl)
                            // console.log(bundleLibVersionCfgUrl, bundleLibVersionCfg)
                            /**  远程bundle版本库 的依赖信息 */
                        ];
                    case 2:
                        bundleLibVersionCfg = _a.sent();
                        dependencies = bundleLibVersionCfg.dependencies;
                        bundleVersions = bundleLibVersionCfg.bundleVersions;
                        allBundles = [];
                        //加入公共的Bundle内容
                        allBundles = allBundles.concat(bundleLibVersionCfg.common);
                        dependLibBundles = this.remoteBundleCfg.remoteBundleLib[bundleLibName].bundleList;
                        dependLibBundles.forEach(function (bundleName) {
                            allBundles = allBundles.concat([bundleName]);
                            // 为了查找循环依赖吧==微测试
                            var dependenciesInfo = _this.getDependByName(dependencies, bundleName);
                            if (dependenciesInfo) {
                                allBundles = allBundles.concat(dependenciesInfo);
                            }
                        });
                        //去重
                        allBundles = allBundles.reduce(function (pre, cur) { return pre.includes(cur) ? pre : __spreadArrays(pre, [cur]); }, []);
                        srcBundles = allBundles.filter(function (bundleName) {
                            // console.log("bundleName", bundleName)
                            return bundleName.includes("-src");
                        });
                        console.log("所有的Bundle", allBundles.toString());
                        console.log("所有的Bundle-src", srcBundles.toString());
                        allBundles.forEach(function (bundleName) {
                            _this.updateCCRequireJS(bundleName);
                        });
                        i = 0;
                        _a.label = 3;
                    case 3:
                        if (!(i < srcBundles.length)) return [3 /*break*/, 6];
                        curSrcBundleName = srcBundles[i];
                        version_1 = bundleVersions[curSrcBundleName];
                        this.updateGameJsonCfg(curSrcBundleName);
                        // this.updateCCRequireJS(curSrcBundleName)
                        this.updateCCSettingsJS(curSrcBundleName, version_1);
                        return [4 /*yield*/, this.updateSubBundleSrc(targetBundleLibUrl, curSrcBundleName, version_1)];
                    case 4:
                        _a.sent();
                        _a.label = 5;
                    case 5:
                        i++;
                        return [3 /*break*/, 3];
                    case 6: return [2 /*return*/];
                }
            });
        });
    };
    /** 递归查找依赖 */
    AddRemoteBundleModule.prototype.getDependByName = function (dependencies, name) {
        var _this = this;
        var allBundles = [];
        var curDependencies = dependencies[name];
        if (!curDependencies)
            return allBundles;
        curDependencies.forEach(function (bundleName) {
            //不再重复加入
            if (allBundles.indexOf(bundleName) != -1) {
                return;
            }
            allBundles.push(bundleName);
            var newArr = _this.getDependByName(dependencies, bundleName);
            if (newArr && newArr.length > 0) {
                allBundles.push(allBundles);
            }
        });
        return allBundles;
    };
    /** 修改game.json配置 增加分包*/
    AddRemoteBundleModule.prototype.updateGameJsonCfg = function (bundleName) {
        return __awaiter(this, void 0, void 0, function () {
            var PROJECT_DIR, platformFolder, curBuildPath, gameJsonPath, gameJsonStr, gameJson, sameBundle;
            return __generator(this, function (_a) {
                PROJECT_DIR = this.buildGameData.PROJECT_DIR;
                platformFolder = PlatformBuildCfg_1.PlatformFolder[this.buildGameData.platformName];
                curBuildPath = path_1["default"].join(PROJECT_DIR, "build", platformFolder);
                gameJsonPath = path_1["default"].join(curBuildPath, 'game.json');
                if (!fs_1["default"].existsSync(gameJsonPath)) {
                    console.warn("缺少game.json文件", gameJsonPath);
                    return [2 /*return*/];
                }
                gameJsonStr = fs_1["default"].readFileSync(gameJsonPath, 'utf8');
                gameJson = JSON.parse(gameJsonStr);
                sameBundle = gameJson.subpackages.find(function (bundleCfg) { return bundleCfg.name == bundleName; });
                if (sameBundle) {
                    console.warn("存在相同名字配置的Bundle", sameBundle);
                    return [2 /*return*/];
                }
                gameJson.subpackages.push({
                    name: bundleName,
                    root: "subpackages/" + bundleName
                });
                fs_1["default"].writeFileSync(gameJsonPath, JSON.stringify(gameJson));
                return [2 /*return*/];
            });
        });
    };
    /** 修改 ccRequire.js 代码,加入index.js */
    AddRemoteBundleModule.prototype.updateCCRequireJS = function (bundleName) {
        return __awaiter(this, void 0, void 0, function () {
            var PROJECT_DIR, platformFolder, curBuildPath, ccRequirePath, ccRequireStr;
            return __generator(this, function (_a) {
                PROJECT_DIR = this.buildGameData.PROJECT_DIR;
                platformFolder = PlatformBuildCfg_1.PlatformFolder[this.buildGameData.platformName];
                curBuildPath = path_1["default"].join(PROJECT_DIR, "build", platformFolder);
                ccRequirePath = path_1["default"].join(curBuildPath, 'ccRequire.js');
                if (!fs_1["default"].existsSync(ccRequirePath)) {
                    console.warn("缺少 ccRequire.js 文件", ccRequirePath);
                    return [2 /*return*/];
                }
                ccRequireStr = fs_1["default"].readFileSync(ccRequirePath, 'utf8');
                // console.log(ccRequireStr)
                ccRequireStr = ccRequireStr.replace("// tail", "'src/scripts/" + bundleName + "/index.js' () { return {} },\n// tail");
                fs_1["default"].writeFileSync(ccRequirePath, ccRequireStr);
                return [2 /*return*/];
            });
        });
    };
    /** 修改 settings.js 代码,加入远程包等信息 */
    AddRemoteBundleModule.prototype.updateCCSettingsJS = function (bundleName, version) {
        return __awaiter(this, void 0, void 0, function () {
            var PROJECT_DIR, platformFolder, curBuildPath, ccSettingPath, tempData, subpackages, bundleVers, ccSettingStr;
            return __generator(this, function (_a) {
                PROJECT_DIR = this.buildGameData.PROJECT_DIR;
                platformFolder = PlatformBuildCfg_1.PlatformFolder[this.buildGameData.platformName];
                curBuildPath = path_1["default"].join(PROJECT_DIR, "build", platformFolder);
                ccSettingPath = path_1["default"].join(curBuildPath, "src", 'settings.js');
                if (!fs_1["default"].existsSync(ccSettingPath)) {
                    console.warn("缺少 settings.js 文件", ccSettingPath);
                    return [2 /*return*/];
                }
                // @ts-ignore
                if (!global.window)
                    global.window = {};
                // @ts-ignore
                require(ccSettingPath);
                tempData = window._CCSettings;
                subpackages = tempData.subpackages;
                bundleVers = tempData.bundleVers;
                bundleVers[bundleName] = version;
                if (subpackages.indexOf(bundleName) != -1) {
                    console.warn("settings.js 存在相同名字配置的Bundle", bundleName);
                }
                else {
                    subpackages.push(bundleName);
                }
                ccSettingStr = JSON.stringify(tempData);
                ccSettingStr = "window._CCSettings=" + ccSettingStr;
                // ccSettingStr.replace("// tail", "'src/scripts/" + bundleName + "/index.js' () { return {} },\n// tail")
                fs_1["default"].writeFileSync(ccSettingPath, ccSettingStr);
                return [2 /*return*/];
            });
        });
    };
    /** 下载远程包代码到分包 */
    AddRemoteBundleModule.prototype.updateSubBundleSrc = function (targetBundleLibUrl, bundleName, version) {
        return __awaiter(this, void 0, void 0, function () {
            var indexJsUrl, configJsonUrl, indexJsStr, configJsonStr, PROJECT_DIR, platformFolder, subpackages, indexJsPath, configJsonPath;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        indexJsUrl = targetBundleLibUrl + "/" + bundleName + "/" + "index." + version + ".js";
                        configJsonUrl = targetBundleLibUrl + "/" + bundleName + "/" + "config." + version + ".json";
                        return [4 /*yield*/, this.getRemoteFile(indexJsUrl)];
                    case 1:
                        indexJsStr = (_a.sent()).data;
                        return [4 /*yield*/, this.getRemoteFile(configJsonUrl)];
                    case 2:
                        configJsonStr = (_a.sent()).data;
                        PROJECT_DIR = this.buildGameData.PROJECT_DIR;
                        platformFolder = PlatformBuildCfg_1.PlatformFolder[this.buildGameData.platformName];
                        subpackages = path_1["default"].join(PROJECT_DIR, "build", platformFolder, "subpackages");
                        indexJsPath = path_1["default"].join(subpackages, bundleName, "game.js");
                        configJsonPath = path_1["default"].join(subpackages, bundleName, "config." + version + ".json");
                        // console.log("写入", indexJsPath)
                        // console.log("写入", configJsonPath)
                        console.log("写入远程代码子包【" + bundleName + "】");
                        FileUtil_1["default"].mkdirsSync(path_1["default"].join(subpackages, bundleName));
                        fs_1["default"].writeFileSync(indexJsPath, indexJsStr);
                        fs_1["default"].writeFileSync(configJsonPath, configJsonStr);
                        return [2 /*return*/];
                }
            });
        });
    };
    /** 获取远程文件内容 */
    AddRemoteBundleModule.prototype.getRemoteJson = function (fileUrl) {
        return __awaiter(this, void 0, void 0, function () {
            var bundleLibCfgReslut, bundleLibCfgStr, bundleLibCfg;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.getRemoteFile(fileUrl)];
                    case 1:
                        bundleLibCfgReslut = _a.sent();
                        bundleLibCfgStr = bundleLibCfgReslut.data;
                        bundleLibCfg = JSON.parse(bundleLibCfgStr);
                        return [2 /*return*/, bundleLibCfg];
                }
            });
        });
    };
    /** 获取远程文件内容 */
    AddRemoteBundleModule.prototype.getRemoteFile = function (fileUrl) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, new Promise(function (resolve, reject) {
                        request_1["default"].get({
                            url: fileUrl
                        }, function (error, response, body) {
                            if (!error && response.statusCode == 200) {
                                // console.log(body) // 请求成功的处理逻辑
                                resolve({
                                    status: true,
                                    data: body
                                });
                            }
                            else {
                                resolve({
                                    status: false,
                                    data: error || (response && response.statusCode)
                                });
                            }
                        });
                    })];
            });
        });
    };
    return AddRemoteBundleModule;
}());
exports["default"] = AddRemoteBundleModule;
