import * as __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ from "react/jsx-runtime";
import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
import * as __WEBPACK_EXTERNAL_MODULE__tachybase_requirejs__ from "@tachybase/requirejs";
import * as __WEBPACK_EXTERNAL_MODULE__tachybase_schema__ from "@tachybase/schema";
import * as __WEBPACK_EXTERNAL_MODULE__tachybase_sdk__ from "@tachybase/sdk";
import * as __WEBPACK_EXTERNAL_MODULE_lodash__ from "lodash";
import * as __WEBPACK_EXTERNAL_MODULE_react_dom_client__ from "react-dom/client";
import * as __WEBPACK_EXTERNAL_MODULE_react_i18next__ from "react-i18next";
import * as __WEBPACK_EXTERNAL_MODULE_react_router_dom__ from "react-router-dom";
import * as __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__ from "../api-client/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__data_source_collection_field_CollectionField_mjs__ from "../data-source/collection-field/CollectionField.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__data_source_components_DataSourceApplicationProvider_mjs__ from "../data-source/components/DataSourceApplicationProvider.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__data_source_data_block_DataBlockProvider_mjs__ from "../data-source/data-block/DataBlockProvider.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__data_source_data_source_DataSourceManager_mjs__ from "../data-source/data-source/DataSourceManager.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__i18n_index_mjs__ from "../i18n/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__style_css_variable_index_mjs__ from "../style/css-variable/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__style_theme_index_mjs__ from "../style/theme/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__AppSchemaComponentProvider_mjs__ from "./AppSchemaComponentProvider.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__AttachmentPreviewManager_mjs__ from "./AttachmentPreviewManager.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__components_index_mjs__ from "./components/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__NoticesManager_mjs__ from "./NoticesManager.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__PluginContextMenu_mjs__ from "./PluginContextMenu.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__PluginManager_mjs__ from "./PluginManager.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__RouterManager_mjs__ from "./RouterManager.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__schema_initializer_index_mjs__ from "./schema-initializer/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__schema_initializer_components_index_mjs__ from "./schema-initializer/components/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__schema_settings_index_mjs__ from "./schema-settings/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__SystemSettingsManager_mjs__ from "./SystemSettingsManager.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__TrackingManager_mjs__ from "./TrackingManager.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__UserSettingsManager_mjs__ from "./UserSettingsManager.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__utils_index_mjs__ from "./utils/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__utils_globalDeps_mjs__ from "./utils/globalDeps.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__WebSocketClient_mjs__ from "./WebSocketClient.mjs";
function _define_property(obj, key, value) {
    if (key in obj) Object.defineProperty(obj, key, {
        value: value,
        enumerable: true,
        configurable: true,
        writable: true
    });
    else obj[key] = value;
    return obj;
}
class Application {
    get pm() {
        return this.pluginManager;
    }
    get adminUrl() {
        if ('main' === this.name) return '/admin/';
        return "/apps/".concat(this.name, "/admin/");
    }
    initRequireJs() {
        this.requirejs = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_requirejs__.getRequireJs)();
        (0, __WEBPACK_EXTERNAL_MODULE__utils_globalDeps_mjs__.defineGlobalDeps)(this.requirejs);
        window.define = this.requirejs.define;
        window.require = this.requirejs.require;
    }
    addDefaultProviders() {
        this.use(__WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__.APIClientProvider, {
            apiClient: this.apiClient
        });
        this.use(__WEBPACK_EXTERNAL_MODULE_react_i18next__.I18nextProvider, {
            i18n: this.i18n
        });
        this.use(__WEBPACK_EXTERNAL_MODULE__style_theme_index_mjs__.GlobalThemeProvider);
        this.use(__WEBPACK_EXTERNAL_MODULE__style_css_variable_index_mjs__.CSSVariableProvider);
        this.use(__WEBPACK_EXTERNAL_MODULE__AppSchemaComponentProvider_mjs__.AppSchemaComponentProvider, {
            designable: this.options.designable,
            appName: this.name,
            components: this.components,
            scope: this.scopes
        });
        this.use(__WEBPACK_EXTERNAL_MODULE__style_theme_index_mjs__.AntdAppProvider);
        this.use(__WEBPACK_EXTERNAL_MODULE__data_source_components_DataSourceApplicationProvider_mjs__.DataSourceApplicationProvider, {
            dataSourceManager: this.dataSourceManager
        });
    }
    addReactRouterComponents() {
        this.addComponents({
            Link: __WEBPACK_EXTERNAL_MODULE_react_router_dom__.Link,
            Navigate: __WEBPACK_EXTERNAL_MODULE_react_router_dom__.Navigate,
            NavLink: __WEBPACK_EXTERNAL_MODULE_react_router_dom__.NavLink
        });
    }
    addRoutes() {
        this.router.add('not-found', {
            path: '*',
            Component: this.components['AppNotFound']
        });
        this.router.add('share', {
            path: '/share',
            Component: __WEBPACK_EXTERNAL_MODULE__components_index_mjs__.SharePage
        });
        this.router.add('share.page', {
            path: '/share/:name',
            Component: __WEBPACK_EXTERNAL_MODULE__components_index_mjs__.ShareSchemaComponent
        });
        this.router.add('share.notAuthorized', {
            path: '/share/not-authorized',
            element: null
        });
    }
    getOptions() {
        return this.options;
    }
    getPublicPath() {
        return this.options.publicPath || '/';
    }
    getName() {
        return (0, __WEBPACK_EXTERNAL_MODULE__tachybase_sdk__.getSubAppName)(this.getPublicPath()) || null;
    }
    getApiUrl() {
        let pathname = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : '';
        let baseURL = this.apiClient.axios['defaults']['baseURL'];
        if (!baseURL.startsWith('http://') && !baseURL.startsWith('https://')) {
            const { protocol, host } = window.location;
            baseURL = "".concat(protocol, "//").concat(host).concat(baseURL);
        }
        return baseURL.replace(/\/$/g, '') + '/' + pathname.replace(/^\//g, '');
    }
    getRouteUrl(pathname) {
        return this.options.publicPath.replace(/\/$/g, '') + pathname;
    }
    getHref(pathname) {
        const name = this.name;
        if (name && 'main' !== name) return this.getPublicPath() + 'apps/' + name + '/' + pathname.replace(/^\//g, '');
        return this.getPublicPath() + pathname.replace(/^\//g, '');
    }
    getCollectionManager(dataSource) {
        var _this_dataSourceManager_getDataSource;
        return null === (_this_dataSourceManager_getDataSource = this.dataSourceManager.getDataSource(dataSource)) || void 0 === _this_dataSourceManager_getDataSource ? void 0 : _this_dataSourceManager_getDataSource.collectionManager;
    }
    getComposeProviders() {
        const Providers = (0, __WEBPACK_EXTERNAL_MODULE__utils_index_mjs__.compose)(...this.providers)(__WEBPACK_EXTERNAL_MODULE__components_index_mjs__.BlankComponent);
        Providers.displayName = 'Providers';
        return Providers;
    }
    use(component, props) {
        return this.addProvider(component, props);
    }
    addProvider(component, props) {
        return this.providers.push([
            component,
            props
        ]);
    }
    addProviders(providers) {
        providers.forEach((provider)=>{
            if (Array.isArray(provider)) this.addProvider(provider[0], provider[1]);
            else this.addProvider(provider);
        });
    }
    async load() {
        let loadFailed = false;
        this.ws.on('message', (event)=>{
            var _data_payload;
            const data = JSON.parse(event.data);
            if (null == data ? void 0 : null === (_data_payload = data.payload) || void 0 === _data_payload ? void 0 : _data_payload.refresh) {
                window.location.reload();
                return;
            }
            if ('notification' === data.type) {
                var _data_payload1, _data_payload2;
                this.notification[(null === (_data_payload1 = data.payload) || void 0 === _data_payload1 ? void 0 : _data_payload1.type) || 'info']({
                    message: null === (_data_payload2 = data.payload) || void 0 === _data_payload2 ? void 0 : _data_payload2.message
                });
                return;
            }
            if ('notice' === data.type) this.noticeManager.on(data.payload);
            const maintaining = 'maintaining' === data.type && 'APP_RUNNING' !== data.payload.code;
            if (maintaining) {
                this.maintaining = true;
                this.error = data.payload;
            } else {
                if (loadFailed) {
                    window.location.reload();
                    return;
                }
                this.maintaining = false;
                this.maintained = true;
                this.error = null;
            }
        });
        this.ws.on('serverDown', ()=>{
            this.maintaining = true;
            this.maintained = true;
        });
        this.ws.connect();
        try {
            this.loading = true;
            await this.pm.load();
        } catch (error) {
            var _error_response_data, _error_response, _error_response_data_errors, _error_response_data1, _error_response1;
            if (this.ws.enabled) await new Promise((resolve)=>{
                setTimeout(()=>resolve(null), 1000);
            });
            loadFailed = true;
            const others = (null == error ? void 0 : null === (_error_response = error.response) || void 0 === _error_response ? void 0 : null === (_error_response_data = _error_response.data) || void 0 === _error_response_data ? void 0 : _error_response_data.error) || (null == error ? void 0 : null === (_error_response1 = error.response) || void 0 === _error_response1 ? void 0 : null === (_error_response_data1 = _error_response1.data) || void 0 === _error_response_data1 ? void 0 : null === (_error_response_data_errors = _error_response_data1.errors) || void 0 === _error_response_data_errors ? void 0 : _error_response_data_errors[0]) || {
                message: null == error ? void 0 : error.message
            };
            this.error = {
                code: 'LOAD_ERROR',
                ...others
            };
            console.error(error, this.error);
        }
        this.loading = false;
    }
    getComponent(Component) {
        let isShowError = !(arguments.length > 1) || void 0 === arguments[1] || arguments[1];
        const showError = (msg)=>isShowError && console.error(msg);
        if (!Component) {
            showError("getComponent called with ".concat(Component));
            return;
        }
        if ('function' == typeof Component) return Component;
        if ('string' == typeof Component) {
            const res = (0, __WEBPACK_EXTERNAL_MODULE_lodash__.get)(this.components, Component);
            if (!res) {
                showError("Component ".concat(Component, " not found"));
                return;
            }
            return res;
        }
        showError("Component ".concat(Component, " should be a string or a React component"));
    }
    renderComponent(Component, props) {
        return /*#__PURE__*/ __WEBPACK_EXTERNAL_MODULE_react__["default"].createElement(this.getComponent(Component), props);
    }
    addComponent(component, name) {
        const componentName = name || component.displayName || component.name;
        if (!componentName) {
            console.error('Component must have a displayName or pass name as second argument');
            return;
        }
        (0, __WEBPACK_EXTERNAL_MODULE_lodash__.set)(this.components, componentName, component);
    }
    addComponents(components) {
        Object.keys(components).forEach((name)=>{
            this.addComponent(components[name], name);
        });
    }
    addScopes(scopes) {
        this.scopes = (0, __WEBPACK_EXTERNAL_MODULE_lodash__.merge)(this.scopes, scopes);
    }
    getRootComponent() {
        const Root = ()=>/*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__components_index_mjs__.AppComponent, {
                app: this
            });
        return Root;
    }
    mount(containerOrSelector) {
        const container = (0, __WEBPACK_EXTERNAL_MODULE__utils_index_mjs__.normalizeContainer)(containerOrSelector);
        if (!container) return;
        const App = this.getRootComponent();
        const root = (0, __WEBPACK_EXTERNAL_MODULE_react_dom_client__.createRoot)(container);
        root.render(/*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(App, {}));
        return root;
    }
    addFieldInterfaceComponentOption(fieldName, componentOption) {
        return this.dataSourceManager.collectionFieldInterfaceManager.addFieldInterfaceComponentOption(fieldName, componentOption);
    }
    addGlobalVar(key, value) {
        (0, __WEBPACK_EXTERNAL_MODULE_lodash__.set)(this.globalVars, key, value);
    }
    getGlobalVar(key) {
        return (0, __WEBPACK_EXTERNAL_MODULE_lodash__.get)(this.globalVars, key);
    }
    constructor(options = {}){
        _define_property(this, "options", void 0);
        _define_property(this, "providers", void 0);
        _define_property(this, "router", void 0);
        _define_property(this, "scopes", void 0);
        _define_property(this, "i18n", void 0);
        _define_property(this, "ws", void 0);
        _define_property(this, "apiClient", void 0);
        _define_property(this, "components", void 0);
        _define_property(this, "pluginManager", void 0);
        _define_property(this, "systemSettingsManager", void 0);
        _define_property(this, "userSettingsManager", void 0);
        _define_property(this, "devDynamicImport", void 0);
        _define_property(this, "requirejs", void 0);
        _define_property(this, "notification", void 0);
        _define_property(this, "schemaInitializerManager", void 0);
        _define_property(this, "schemaSettingsManager", void 0);
        _define_property(this, "dataSourceManager", void 0);
        _define_property(this, "noticeManager", void 0);
        _define_property(this, "trackingManager", void 0);
        _define_property(this, "pluginContextMenu", void 0);
        _define_property(this, "AttachmentPreviewManager", void 0);
        _define_property(this, "name", void 0);
        _define_property(this, "globalVars", void 0);
        _define_property(this, "loading", void 0);
        _define_property(this, "maintained", void 0);
        _define_property(this, "maintaining", void 0);
        _define_property(this, "error", void 0);
        this.options = options;
        this.providers = [];
        this.scopes = {};
        this.components = {
            DataBlockProvider: __WEBPACK_EXTERNAL_MODULE__data_source_data_block_DataBlockProvider_mjs__.DataBlockProvider,
            ...__WEBPACK_EXTERNAL_MODULE__components_index_mjs__.defaultAppComponents,
            ...__WEBPACK_EXTERNAL_MODULE__schema_initializer_components_index_mjs__,
            CollectionField: __WEBPACK_EXTERNAL_MODULE__data_source_collection_field_CollectionField_mjs__.CollectionField
        };
        this.globalVars = {};
        this.loading = true;
        this.maintained = false;
        this.maintaining = false;
        this.error = null;
        this.initRequireJs();
        (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.define)(this, {
            maintained: __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.observable.ref,
            loading: __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.observable.ref,
            maintaining: __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.observable.ref,
            error: __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.observable.ref
        });
        this.devDynamicImport = options.devDynamicImport;
        this.scopes = (0, __WEBPACK_EXTERNAL_MODULE_lodash__.merge)(this.scopes, options.scopes);
        this.components = (0, __WEBPACK_EXTERNAL_MODULE_lodash__.merge)(this.components, options.components);
        this.apiClient = options.apiClient instanceof __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__.APIClient ? options.apiClient : new __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__.APIClient(options.apiClient);
        this.apiClient.app = this;
        this.i18n = options.i18n || __WEBPACK_EXTERNAL_MODULE__i18n_index_mjs__.i18n;
        this.router = new __WEBPACK_EXTERNAL_MODULE__RouterManager_mjs__.RouterManager(options.router, this);
        this.schemaSettingsManager = new __WEBPACK_EXTERNAL_MODULE__schema_settings_index_mjs__.SchemaSettingsManager(options.schemaSettings, this);
        this.pluginManager = new __WEBPACK_EXTERNAL_MODULE__PluginManager_mjs__.PluginManager(options.plugins, options.loadRemotePlugins, this);
        this.schemaInitializerManager = new __WEBPACK_EXTERNAL_MODULE__schema_initializer_index_mjs__.SchemaInitializerManager(options.schemaInitializers, this);
        this.dataSourceManager = new __WEBPACK_EXTERNAL_MODULE__data_source_data_source_DataSourceManager_mjs__.DataSourceManager(options.dataSourceManager, this);
        this.noticeManager = new __WEBPACK_EXTERNAL_MODULE__NoticesManager_mjs__.NoticeManager(this);
        this.trackingManager = new __WEBPACK_EXTERNAL_MODULE__TrackingManager_mjs__.TrackingManager(this);
        this.addDefaultProviders();
        this.addReactRouterComponents();
        this.addProviders(options.providers || []);
        this.ws = new __WEBPACK_EXTERNAL_MODULE__WebSocketClient_mjs__.WebSocketClient(options.ws, this);
        this.systemSettingsManager = new __WEBPACK_EXTERNAL_MODULE__SystemSettingsManager_mjs__.SystemSettingsManager(options.pluginSettings, this);
        this.userSettingsManager = new __WEBPACK_EXTERNAL_MODULE__UserSettingsManager_mjs__.UserSettingsManager(options.userSettings, this);
        this.addRoutes();
        this.name = this.options.name || (0, __WEBPACK_EXTERNAL_MODULE__tachybase_sdk__.getSubAppName)(options.publicPath) || 'main';
        this.pluginContextMenu = new __WEBPACK_EXTERNAL_MODULE__PluginContextMenu_mjs__.PluginContextMenu(options.pluginMenuItems);
        this.AttachmentPreviewManager = new __WEBPACK_EXTERNAL_MODULE__AttachmentPreviewManager_mjs__.AttachmentPreviewManager(options.attachmentItem, this);
        this.i18n.on('languageChanged', (lng)=>{
            this.apiClient.auth.locale = lng;
        });
    }
}
export { Application };
