import { jsx } from "react/jsx-runtime";
import react, { createContext, useContext } from "react";
import { LoadingOutlined } from "@ant-design/icons";
import { Button, Result } from "antd";
import { useTranslation } from "react-i18next";
import { CardItem, useSchemaComponentContext } from "../../schema-component/index.mjs";
import { CollectionDeletedPlaceholder } from "../components/CollectionDeletedPlaceholder.mjs";
import { useDataSourceManager } from "./DataSourceManagerProvider.mjs";
const DataSourceContext = /*#__PURE__*/ createContext(null);
DataSourceContext.displayName = 'DataSourceContext';
const DataSourceProvider = (param)=>{
    let { children, dataSource } = param;
    const dataSourceManager = useDataSourceManager();
    const { t } = useTranslation();
    const { refresh } = useSchemaComponentContext();
    const [_, setRandom] = react.useState(0);
    const dataSourceValue = dataSourceManager.getDataSource(dataSource);
    if (!dataSourceValue) return /*#__PURE__*/ jsx(CollectionDeletedPlaceholder, {
        type: "DataSource",
        name: dataSource
    });
    if ('loading-failed' === dataSourceValue.status) return /*#__PURE__*/ jsx(CollectionDeletedPlaceholder, {
        type: "DataSource",
        name: dataSourceValue.displayName || dataSource,
        message: dataSourceValue.errorMessage || 'loading failed'
    });
    if ('loading' === dataSourceValue.status || 'reloading' === dataSourceValue.status) return /*#__PURE__*/ jsx(CardItem, {
        children: /*#__PURE__*/ jsx(Result, {
            icon: /*#__PURE__*/ jsx(LoadingOutlined, {}),
            title: "".concat(dataSourceValue.displayName || dataSource, " ").concat(t('data source'), " ").concat(t('loading'), "..."),
            extra: /*#__PURE__*/ jsx(Button, {
                type: "primary",
                onClick: ()=>dataSourceValue.reload().then(()=>{
                        refresh();
                        setRandom(Math.random());
                    }),
                children: t('Refresh')
            })
        })
    });
    return /*#__PURE__*/ jsx(DataSourceContext.Provider, {
        value: dataSourceValue,
        children: children
    });
};
function useDataSource() {
    const context = useContext(DataSourceContext);
    return context;
}
function useDataSourceKey() {
    const context = useContext(DataSourceContext);
    return null == context ? void 0 : context.key;
}
export { DataSourceContext, DataSourceProvider, useDataSource, useDataSourceKey };
