var _a;
import { __assign, __awaiter, __generator } from "tslib";
import { ECodeType } from '@cloudbase/cals';
import { evalCodeCodules, } from './parser/base';
import { StateParser, ComputedParser, LifeCycleParser, HandlerParser, NormalModuleParser, RendererParser, } from './parser/index';
export { generateStyleModule, generateStyleModuleMap } from './parser/lessParser';
var moduleParsers = (_a = {},
    _a[ECodeType.LIFECYCLE] = new LifeCycleParser(),
    _a[ECodeType.COMPUTEDN] = new ComputedParser(),
    _a[ECodeType.STATE] = new StateParser(),
    _a[ECodeType.NORMAL_MODULE] = new NormalModuleParser(),
    _a[ECodeType.HANDLER_FN] = new HandlerParser(),
    _a[ECodeType.RENDERER] = new RendererParser(),
    _a);
// 用于页面内通信
var lastError = [];
function addError(e, file) {
    var err = { file: file, message: e.message || e.stack };
    lastError.push(err);
}
export var lowcodeContext = {};
// export const widgetsContext = {} as WidgetsContext;
// Just for debug
// Object.defineProperty(window, '__widgetsContext', {
//   get: () => widgetsContext,
// });
Object.defineProperty(window, '__lowcodeContext', {
    get: function () { return 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
 */
export 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 __awaiter(this, void 0, void 0, function () {
        var allModules, _loop_1, pageId, result;
        return __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 __assign(__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(lowcodeContext, result);
                    return [2 /*return*/, lowcodeContext];
            }
        });
    });
}
export function applyLowcode(allModules, opts) {
    var _a;
    return __awaiter(this, void 0, void 0, function () {
        var innerEvalContext, type, evaledModules, _loop_2, pageId, type;
        return __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*/, 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];
            }
        });
    });
}
// 去掉css 代码
function filterCssCodeModules(modules) {
    if (modules === void 0) { modules = []; }
    return modules.filter(function (module) { return module.codeType !== ECodeType.STYLE && module.codeType !== ECodeType.THEME; });
}
// export function cleanWidgetsContext() {
//   for (let key in widgetsContext) {
//     delete widgetsContext[key];
//   }
// }
export function cleanLowcodeContext() {
    // @ts-ignore For debugging
    Object.keys(lowcodeContext).forEach(function (key) {
        delete lowcodeContext[key];
    });
}
//# sourceMappingURL=lowcode.js.map