import { __awaiter } from "tslib";
import React from "react";
import { RuntimeContext } from "@qorebase/app-runtime/src/RuntimeContext";
import { useForm } from "react-hook-form";
import qoreStorageClient from "../hooks/qoreStorageClient";
import { useRouter } from "next/router";
import EditorContext from "@qorebase/app-runtime/src/EditorContext";
import { DefaultApiFactory } from "@qorebase/sdk";
import useSWRImmutable from "swr/immutable";
import { importLocalNpmComponent, listLocalComponents, } from "@qorebase/app-runtime/src/utils/importComponent";
import { convertFileToPublicURL } from "../utils/convertFileToPublicURL";
import { transformQorebaseSchema } from "@qorebase/app-runtime/src/utils/normalizeSchema";
import { initialApp } from "@qorebase/app-runtime/src/InitialData";
import { importBuiltins, useImportComponentLazy, } from "@qorebase/app-runtime/src/builtinComponents";
import { usePageParam } from "@qorebase/app-runtime/src/hooks/usePageParam";
import { useInitializePageCache } from "@qorebase/app-runtime/src/hooks/useFetchPage";
export default React.memo(function TitleBar() {
    var _a;
    const router = useRouter();
    const form = useForm({ mode: "onBlur", defaultValues: { title: "" } });
    const runtimeActions = RuntimeContext.useActions();
    const runtimeHistory = RuntimeContext.useHistory();
    const pageParam = usePageParam();
    const page = RuntimeContext.useSelectState((state) => state.maps.page[pageParam]);
    const applications = qoreStorageClient.view("application-detail").useListRow({
        params: {
            appId: router.query.appID,
            projectId: router.query.projectID,
        },
        populate: ["project"],
        limit: 1,
    });
    const currentApp = React.useMemo(() => applications.data[0], [applications.data]);
    const { data: releases } = qoreStorageClient.table("release_log").useListRow({
        condition: {
            release: {
                project: (_a = currentApp === null || currentApp === void 0 ? void 0 : currentApp.project) === null || _a === void 0 ? void 0 : _a.id,
            },
            stage: "staging",
        },
        orderBy: {
            updated_at: "DESC",
        },
        limit: 1,
    }, {
        skip: !currentApp,
    });
    const qoreDataEndpoint = React.useMemo(() => {
        var _a, _b;
        const endpoint = (_b = (_a = releases === null || releases === void 0 ? void 0 : releases[0]) === null || _a === void 0 ? void 0 : _a.user_overrides) === null || _b === void 0 ? void 0 : _b["qore-data"].domains.split(",")[0];
        return endpoint && `https://${endpoint}`;
    }, [releases]);
    const adminSecret = React.useMemo(() => { var _a, _b; return (_b = (_a = releases === null || releases === void 0 ? void 0 : releases[0]) === null || _a === void 0 ? void 0 : _a.user_overrides) === null || _b === void 0 ? void 0 : _b["qore-data"].admin_secret; }, [releases]);
    const qoreDataApi = DefaultApiFactory({
        apiKey: adminSecret,
        isJsonMime: (mime) => {
            const jsonMime = new RegExp("^(application/json|[^;/ \\t]+/[^;/ \\t]+[+]json)[ \\t]*(;.*)?$", "i");
            return (mime !== null &&
                (jsonMime.test(mime) ||
                    mime.toLowerCase() === "application/json-patch+json"));
        },
    }, qoreDataEndpoint);
    const { data: schema } = useSWRImmutable([qoreDataEndpoint, "schema"], () => __awaiter(this, void 0, void 0, function* () {
        const { data } = yield qoreDataApi.getSchema();
        return data;
    }), {
        isPaused: () => !(qoreDataEndpoint && adminSecret),
    });
    React.useEffect(() => {
        if (!page)
            return;
        form.reset({ title: page.title });
    }, [page === null || page === void 0 ? void 0 : page.title]);
    const ready = EditorContext.useSelectState((state) => state.ready);
    const editorActions = EditorContext.useActions();
    const revisionID = EditorContext.useSelectState((state) => state.revisionID);
    const importComponent = useImportComponentLazy();
    useInitializePageCache();
    React.useEffect(() => {
        if (!revisionID || !schema || ready || !qoreDataEndpoint || !adminSecret)
            return;
        (() => __awaiter(this, void 0, void 0, function* () {
            var _a, _b, _c, _d;
            const revisionResult = yield qoreStorageClient.client
                .table("revisions")
                .readRows({
                condition: {
                    id: { $eq: revisionID },
                },
                limit: 1,
            })
                .toPromise();
            const revision = (_a = revisionResult.data) === null || _a === void 0 ? void 0 : _a.nodes[0];
            const appResult = yield qoreStorageClient.client
                .table("applications")
                .readRows({
                condition: {
                    id: { $eq: revision === null || revision === void 0 ? void 0 : revision.apprevision },
                },
            }, { skip: !(revision === null || revision === void 0 ? void 0 : revision.apprevision) })
                .toPromise();
            const app = (_b = appResult.data) === null || _b === void 0 ? void 0 : _b.nodes[0];
            if (!revision || !app)
                return;
            const application = Object.assign(Object.assign(Object.assign({}, initialApp), revision.data), { name: app.name, description: app.description, icon: convertFileToPublicURL("applications", "icon", app.id, app.icon) });
            try {
                const cfg = Object.assign(Object.assign({}, application.config), { projectID: router.query.projectID, appID: router.query.appID });
                const config = Object.assign(Object.assign({}, cfg), { endpoint: qoreDataEndpoint });
                application.config = config;
                editorActions.setQoreDataConfig({
                    endpoint: qoreDataEndpoint,
                    adminSecret: adminSecret,
                });
                const npmComponents = application.components.filter((component) => component.enabled);
                yield Promise.all([
                    ...npmComponents.map((component) => importComponent(component.name)),
                    ...listLocalComponents().map(importLocalNpmComponent),
                    importBuiltins(npmComponents.map((component) => component.name)),
                ]);
                editorActions.setReady(true);
            }
            catch (error) {
                console.error("error", error);
            }
            application.theme = Object.assign({ id: "Light", options: { primaryColor: "#0064ff" }, navigationLayout: "sidebar" }, application.theme);
            if (((_c = application.maps.component.register_role_input) === null || _c === void 0 ? void 0 : _c.properties.roleId) === "") {
                const { data } = yield qoreDataApi.getAllRolesAndPermissions();
                const defaultRole = ((_d = data.roles.filter((role) => !["admin", "public"].includes(role.name))[0]) === null || _d === void 0 ? void 0 : _d.id) || "";
                // @ts-ignore
                application.maps.component.register_role_input.properties.roleId =
                    defaultRole;
            }
            application.schema = transformQorebaseSchema(schema);
            runtimeActions.setApp(application);
            runtimeHistory.clear();
            console.log("app revision loaded", revisionID, revision.id);
        }))();
    }, [revisionID, router.query, ready, schema, editorActions]);
    return null;
});
//# sourceMappingURL=TitleBar.js.map