"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 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 cals_1 = require("@cloudbase/cals");
var base_1 = require("./parser/base");
var index_1 = require("./parser/index");
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);
// 用于页面内通信
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;
    return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
        var allModules, _loop_1, pageId, result;
        return (0, tslib_1.__generator)(this, function (_e) {
            switch (_e.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 (0, tslib_1.__assign)((0, 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, /^.*?\//, pageId + "/") });
                            });
                        allModules[pageId] = quickClone(filterCssCodeModules(modules));
                    };
                    for (pageId in codeModulesMap) {
                        _loop_1(pageId);
                    }
                    return [4 /*yield*/, applyLowcode(allModules, {
                            dependencies: dependencies,
                            onDependencyMiss: onDependencyMiss,
                            runtimeWindow: runtimeWindow,
                        })];
                case 1:
                    result = _e.sent();
                    Object.assign(exports.lowcodeContext, result);
                    return [2 /*return*/, exports.lowcodeContext];
            }
        });
    });
}
exports.generateLowcodeModules = generateLowcodeModules;
function applyLowcode(allModules, opts) {
    return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
        var innerEvalContext, type, evaledModules, _loop_2, pageId, type;
        return (0, tslib_1.__generator)(this, function (_a) {
            switch (_a.label) {
                case 0:
                    innerEvalContext = {};
                    for (type in moduleParsers) {
                        // eslint-disable-line
                        moduleParsers[type].onStart(innerEvalContext);
                    }
                    opts.onBeforeParse && opts.onBeforeParse(innerEvalContext);
                    lastError = [];
                    // @ts-ignore
                    opts.onCodeError = addError;
                    return [4 /*yield*/, (0, base_1.evalCodeCodules)(allModules, opts)];
                case 1:
                    evaledModules = _a.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 " + m.codeType);
                                }
                                return;
                            }
                            try {
                                parser.parseModule(pageId, m);
                            }
                            catch (e) {
                                console.error('Error parse module', m, e);
                            }
                        });
                    };
                    for (pageId in evaledModules) {
                        _loop_2(pageId);
                    }
                    for (type in moduleParsers) {
                        // eslint-disable-line
                        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
    for (var key in exports.lowcodeContext) {
        delete exports.lowcodeContext[key];
    }
}
exports.cleanLowcodeContext = cleanLowcodeContext;
//# sourceMappingURL=lowcode.js.map