"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.cleanLowcodeContext = exports.applyLowcode = exports.generateLowcodeModules = exports.lowcodeContext = exports.generateStyleModuleMap = exports.generateStyleModule = void 0;
var tslib_1 = require("tslib");
var cals_1 = require("@cloudbase/cals");
var base_1 = require("./parser/base");
var index_1 = require("./parser/index");
var lessParser_1 = require("./parser/lessParser");
Object.defineProperty(exports, "generateStyleModule", { enumerable: true, get: function () { return lessParser_1.generateStyleModule; } });
Object.defineProperty(exports, "generateStyleModuleMap", { enumerable: true, get: function () { return lessParser_1.generateStyleModuleMap; } });
var moduleParsers = (_a = {},
    _a[cals_1.ECodeType.LIFECYCLE] = new index_1.LifeCycleParser(),
    _a[cals_1.ECodeType.COMPUTEDN] = new index_1.ComputedParser(),
    _a[cals_1.ECodeType.STATE] = new index_1.StateParser(),
    _a[cals_1.ECodeType.NORMAL_MODULE] = new index_1.NormalModuleParser(),
    _a[cals_1.ECodeType.HANDLER_FN] = new index_1.HandlerParser(),
    _a[cals_1.ECodeType.RENDERER] = new index_1.RendererParser(),
    _a);
// 用于页面内通信
var lastError = [];
function addError(e, file) {
    var err = { file: file, message: e.message || e.stack };
    lastError.push(err);
}
exports.lowcodeContext = {};
// export const widgetsContext = {} as WidgetsContext;
// Just for debug
// Object.defineProperty(window, '__widgetsContext', {
//   get: () => widgetsContext,
// });
Object.defineProperty(window, '__lowcodeContext', {
    get: function () { return exports.lowcodeContext; },
    set: function (value) {
        console.warn('__lowcodeContext can not been set to another value');
    },
});
function quickClone(json) {
    return JSON.parse(JSON.stringify(json));
}
/**
 * Reexecute all low code when updated
 */
function generateLowcodeModules(_a) {
    var runtimeWindow = _a.runtimeWindow, _b = _a.codeModulesMap, codeModulesMap = _b === void 0 ? {} : _b, _c = _a.onDependencyMiss, onDependencyMiss = _c === void 0 ? function () { } : _c, _d = _a.dependencies, dependencies = _d === void 0 ? {} : _d, _e = _a.externals, externals = _e === void 0 ? {} : _e;
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var allModules, _loop_1, pageId, result;
        return tslib_1.__generator(this, function (_f) {
            switch (_f.label) {
                case 0:
                    allModules = {
                        global: quickClone(filterCssCodeModules(codeModulesMap.global)),
                    };
                    _loop_1 = function (pageId) {
                        var modules = pageId === 'global'
                            ? codeModulesMap[pageId]
                            : codeModulesMap[pageId].map(function (module) {
                                var _a, _b;
                                return tslib_1.__assign(tslib_1.__assign({}, module), { path: (_b = (_a = module.path) === null || _a === void 0 ? void 0 : _a.replace) === null || _b === void 0 ? void 0 : _b.call(_a, /^.*?\//, "".concat(pageId, "/")) });
                            });
                        allModules[pageId] = quickClone(filterCssCodeModules(modules));
                    };
                    for (pageId in codeModulesMap) {
                        _loop_1(pageId);
                    }
                    return [4 /*yield*/, applyLowcode(allModules, {
                            dependencies: dependencies,
                            onDependencyMiss: onDependencyMiss,
                            runtimeWindow: runtimeWindow,
                            externals: externals,
                        })];
                case 1:
                    result = _f.sent();
                    Object.assign(exports.lowcodeContext, result);
                    return [2 /*return*/, exports.lowcodeContext];
            }
        });
    });
}
exports.generateLowcodeModules = generateLowcodeModules;
function applyLowcode(allModules, opts) {
    var _a;
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var innerEvalContext, type, evaledModules, _loop_2, pageId, type;
        return tslib_1.__generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    innerEvalContext = {};
                    for (type in moduleParsers) {
                        // eslint-disable-line
                        moduleParsers[type].onStart(innerEvalContext);
                    }
                    (_a = opts.onBeforeParse) === null || _a === void 0 ? void 0 : _a.call(opts, innerEvalContext);
                    lastError = [];
                    // @ts-ignore
                    opts.onCodeError = addError;
                    return [4 /*yield*/, (0, base_1.evalCodeCodules)(allModules, opts)];
                case 1:
                    evaledModules = _b.sent();
                    _loop_2 = function (pageId) {
                        // eslint-disable-line
                        evaledModules[pageId].forEach(function (m) {
                            var parser = moduleParsers[m.codeType];
                            if (!parser) {
                                if (m.codeType !== 'mp_config') {
                                    console.error("Can not handle code module of type ".concat(m.codeType));
                                }
                                return;
                            }
                            try {
                                parser.parseModule(pageId, m);
                            }
                            catch (e) {
                                console.error('Error parse module', m, e);
                            }
                        });
                    };
                    // eslint-disable-next-line no-restricted-syntax
                    for (pageId in evaledModules) {
                        _loop_2(pageId);
                    }
                    // eslint-disable-next-line no-restricted-syntax
                    for (type in moduleParsers) {
                        try {
                            moduleParsers[type].onEnd(innerEvalContext);
                        }
                        catch (e) {
                            console.error('Module parser error', e);
                        }
                    }
                    return [2 /*return*/, innerEvalContext];
            }
        });
    });
}
exports.applyLowcode = applyLowcode;
// 去掉css 代码
function filterCssCodeModules(modules) {
    if (modules === void 0) { modules = []; }
    return modules.filter(function (module) { return module.codeType !== cals_1.ECodeType.STYLE && module.codeType !== cals_1.ECodeType.THEME; });
}
// export function cleanWidgetsContext() {
//   for (let key in widgetsContext) {
//     delete widgetsContext[key];
//   }
// }
function cleanLowcodeContext() {
    // @ts-ignore For debugging
    Object.keys(exports.lowcodeContext).forEach(function (key) {
        delete exports.lowcodeContext[key];
    });
}
exports.cleanLowcodeContext = cleanLowcodeContext;
//# sourceMappingURL=lowcode.js.map