import { __awaiter } from "tslib";
import { Fragment as _Fragment, jsx as _jsx } from "@emotion/react/jsx-runtime";
import { RuntimeContext } from "../RuntimeContext";
import { mutate } from "swr";
import useSWRImmutable from "swr/immutable";
import React from "react";
import { withSuspense } from "../components/PageSuspense";
import { useParams } from "react-router-dom";
import EditorContext from "../EditorContext";
export const useInitializePageCache = () => {
    const ready = EditorContext.useSelectState((state) => state.ready);
    const appID = RuntimeContext.useSelectState((state) => state.config.appID);
    const maps = RuntimeContext.useSelectState((state) => state.maps);
    React.useEffect(() => {
        if (!ready)
            return;
        Object.entries(maps.page).forEach(([pageID, page]) => {
            mutate(`/api/app/${appID}/schema/${pageID}.json`, {
                component: Object.values(maps.component).filter((component) => page.components.some((ref) => ref.component === component.id)),
                page,
            }, {
                revalidate: false,
            });
        });
    }, [ready]);
};
export const useFetchPage = (pageID) => {
    const app = RuntimeContext.useSelectState((state) => state);
    const runtimeActions = RuntimeContext.useActions();
    const fetched = !!app.maps.page[pageID];
    const { data } = useSWRImmutable(`/api/app/${app.config.appID}/schema/${pageID}.json`, (url) => __awaiter(void 0, void 0, void 0, function* () {
        const data = yield fetch(url).then((res) => res.json());
        const newApp = Object.assign(Object.assign({}, app), { maps: {
                component: Object.assign(Object.assign({}, app.maps.component), Object.fromEntries(data.components.map((component) => [component.id, component]))),
                page: Object.assign(Object.assign({}, app.maps.page), { [data.page.id]: data.page }),
            } });
        runtimeActions.setApp(newApp);
        return data;
    }), {
        suspense: !fetched,
        isPaused: () => fetched || !pageID,
    });
    React.useEffect(() => {
        if (!data)
            return;
    }, [data]);
    return fetched;
};
export const PageSchemaLoader = withSuspense(({ children, page, }) => {
    const params = useParams();
    useFetchPage(page !== null && page !== void 0 ? page : params.page);
    return _jsx(_Fragment, { children: children });
});
//# sourceMappingURL=useFetchPage.js.map