"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatDependiencesMap = exports.loadDependiences = exports.injectExternals = void 0;
var tslib_1 = require("tslib");
var React = (0, tslib_1.__importStar)(require("react"));
var ReactDom = (0, tslib_1.__importStar)(require("react-dom"));
var server_1 = (0, tslib_1.__importDefault)(require("react-dom/server"));
var MobxReactLite = (0, tslib_1.__importStar)(require("mobx-react-lite"));
var Mobx = (0, tslib_1.__importStar)(require("mobx"));
var lodash_es_1 = require("lodash-es");
var History = (0, tslib_1.__importStar)(require("history"));
var ReactErrorBoundary = (0, tslib_1.__importStar)(require("react-error-boundary"));
var index_1 = require("../index");
var index_2 = require("./index");
function loadUmdModule(jsUrl, umdModuleName, targetDoc, cache) {
    if (targetDoc === void 0) { targetDoc = document; }
    if (cache === void 0) { cache = false; }
    return new Promise(function (resolve, reject) {
        var win = targetDoc.defaultView;
        if (cache && Object.prototype.hasOwnProperty.call(win, umdModuleName)) {
            resolve(win[umdModuleName]);
        }
        else {
            var script = targetDoc.createElement('script');
            script.setAttribute('src', jsUrl);
            script.setAttribute('class', umdModuleName);
            script.addEventListener('load', function () {
                var win = targetDoc.defaultView;
                if (Object.prototype.hasOwnProperty.call(win, umdModuleName)) {
                    return resolve(win[umdModuleName]);
                }
                else {
                    var error = new Error("Fail to load UMD module " + umdModuleName + " from [" + jsUrl + "].");
                    return reject(error);
                }
            });
            script.addEventListener('error', function (e) {
                var error = new Error("main bundle [" + umdModuleName + "] load failed from [" + jsUrl + "]: " + ((e === null || e === void 0 ? void 0 : e.message) || ''));
                reject(error);
            });
            targetDoc.body.appendChild(script);
        }
    });
}
function loadCssModule(url, bundleName, entryDoc, cache) {
    if (entryDoc === void 0) { entryDoc = document; }
    if (cache === void 0) { cache = false; }
    if (!url) {
        return Promise.resolve();
    }
    return new Promise(function (resolve) {
        var className = "@weda-materials-style-" + bundleName;
        if (cache) {
            var links = Array.from(entryDoc.head.querySelectorAll('link'));
            if (links.find(function (item) { return (item === null || item === void 0 ? void 0 : item.className) === className; })) {
                return resolve();
            }
        }
        var link = entryDoc.createElement('link');
        link.type = 'text/css';
        link.rel = 'stylesheet';
        link.className = className;
        link.href = url;
        link.addEventListener('load', function () { return resolve(); });
        link.addEventListener('error', function (e) {
            console.warn("Load [" + bundleName + "] meta style failed, skip...", e);
            resolve();
        });
        entryDoc.head.appendChild(link);
    });
}
function injectExternals(runtime) {
    if (runtime === void 0) { runtime = index_2.runtime; }
    var externals = {
        // 兼容配置
        react: React,
        React: runtime['React'] || React,
        ReactDOM: runtime['ReactDOM'] || ReactDom,
        ReactDom: ReactDom,
        ReactDomServer: server_1.default,
        Mobx: runtime['mobx'] || Mobx,
        'mobx-react-lite': MobxReactLite,
        MobxReactLite: MobxReactLite,
        LodashGet: lodash_es_1.get,
        LodashRemove: lodash_es_1.remove,
        LodashSet: lodash_es_1.set,
        ReactErrorBoundary: ReactErrorBoundary,
        History: History,
    };
    for (var key in externals) {
        runtime[key] = externals[key];
    }
}
exports.injectExternals = injectExternals;
function loadDependiences(data, options) {
    return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
        var controlPromises, componentPromises, cssPromises, dependencies, runtime, cache, _a, controls, components, res;
        return (0, tslib_1.__generator)(this, function (_b) {
            switch (_b.label) {
                case 0:
                    controlPromises = [];
                    componentPromises = [];
                    cssPromises = [];
                    dependencies = Array.isArray(data) ? data : data.dependencies;
                    runtime = !Array.isArray(data) && data.runtime ? data.runtime : index_2.runtime;
                    cache = typeof options === 'boolean' ? options : (options === null || options === void 0 ? void 0 : options.cache) || false;
                    dependencies.forEach(function (item) {
                        if (!item.isComposite) {
                            controlPromises.push(loadUmdModule(item.controlJsPath ||
                                item.mainJsPath.replace(/\.main\.js/, '.control.js'), "@weapps-materials-control-" + item.name, runtime.document, cache)
                                .then(function (res) {
                                res.name = item.name;
                                res.version = item.version;
                                return res;
                            })
                                .catch(function (e) {
                                console.warn(e);
                                return null;
                            }));
                        }
                        componentPromises.push(loadUmdModule(item.mainJsPath, "@weapps-materials-main-" + item.name, runtime.document, cache).then(function (res) {
                            res.name = item.name;
                            res.isComposite = item.isComposite;
                            return res;
                        }, function (e) {
                            console.warn(e);
                            return null;
                        }));
                        cssPromises.push(loadCssModule(item.mainCssPath, item.name, runtime.document, cache));
                    });
                    return [4 /*yield*/, Promise.all([controlPromises, componentPromises, cssPromises].map(function (arr) {
                            return Promise.all(arr);
                        }))];
                case 1:
                    _a = tslib_1.__read.apply(void 0, [_b.sent(), 2]), controls = _a[0], components = _a[1];
                    res = formatDependiencesMap(components, controls);
                    return [2 /*return*/, res];
            }
        });
    });
}
exports.loadDependiences = loadDependiences;
function formatDependiencesMap(components, controls) {
    var componentsMap = {};
    var componentActionsMap = {};
    components
        .filter(function (item) { return !!item; })
        .forEach(function (lib) {
        var _a, _b;
        var _c = lib.schemaVersion, schemaVersion = _c === void 0 ? '' : _c;
        var isPlainProps = true;
        if (lib.isComposite ||
            isNaN(Number((_a = schemaVersion.split('.')) === null || _a === void 0 ? void 0 : _a[0])) ||
            Number((_b = schemaVersion.split('.')) === null || _b === void 0 ? void 0 : _b[0]) < 3) {
            isPlainProps = false;
        }
        var _loop_1 = function (componentName) {
            var Field = lib.components[componentName];
            componentsMap[lib.name + ":" + componentName] = function (props) {
                var processedProps = (0, index_1.resolveComponentProps)(props, isPlainProps);
                return React.createElement(Field, (0, tslib_1.__assign)({}, processedProps));
            };
        };
        for (var componentName in lib.components || {}) {
            _loop_1(componentName);
        }
        for (var actionName in lib.actions) {
            componentActionsMap[lib.name + ":" + actionName] =
                lib.actions[actionName];
        }
    });
    var controlMap = controls
        .filter(function (item) { return !!item; })
        .reduce(function (map, lib) {
        map[lib.name + "@" + lib.version] = lib;
        return map;
    }, {});
    // console.log('controlMap', controlMap);
    // console.log('componentsMap', componentsMap);
    return {
        controlMap: controlMap,
        componentsMap: componentsMap,
        componentActionsMap: componentActionsMap,
    };
}
exports.formatDependiencesMap = formatDependiencesMap;
//# sourceMappingURL=dependiences.js.map