import { __awaiter } from "tslib";
import { jsx as _jsx, Fragment as _Fragment } from "@emotion/react/jsx-runtime";
import React from "react";
import { Save } from "@feedloop/icon";
import { Button, useDisclosure, } from "@chakra-ui/react";
import { useRouter } from "next/router";
import qoreStorageClient from "../hooks/qoreStorageClient";
import EditorContext from "@qorebase/app-runtime/src/EditorContext";
import { RuntimeContext } from "@qorebase/app-runtime/src/RuntimeContext";
import { debounce } from "lodash/fp";
import dayjs from "dayjs";
import useSave from "../hooks/useSaveApp";
export default function SaveButton() {
    const router = useRouter();
    const activeWindow = EditorContext.useSelectState((state) => state.activeWindow);
    const appId = router.query.appID;
    const { isOpen, onOpen, onClose } = useDisclosure();
    const editorActions = EditorContext.useActions();
    const runtimeActions = RuntimeContext.useActions();
    const app = RuntimeContext.useSelectState((state) => state);
    const { isDirty, clean } = RuntimeContext.useDirty();
    const revisionId = EditorContext.useSelectState((state) => state.revisionID);
    const { data: currentRevision } = qoreStorageClient
        .table("revisions")
        .useGetRow(revisionId, { skip: !revisionId });
    const { user } = qoreStorageClient.useCurrentUser();
    const updateApp = qoreStorageClient.table("applications").useUpdateRow();
    const insertRevision = qoreStorageClient.table("revisions").useInsertRow();
    const updateRevision = qoreStorageClient.table("revisions").useUpdateRow();
    const autosave = React.useCallback(debounce(5000, (userId, appId, app) => __awaiter(this, void 0, void 0, function* () {
        if (!userId)
            return;
        const shouldUpdate = (currentRevision === null || currentRevision === void 0 ? void 0 : currentRevision.name) === "autosave" &&
            dayjs(currentRevision === null || currentRevision === void 0 ? void 0 : currentRevision.updated_at).add(1, "h").isAfter(dayjs());
        yield (shouldUpdate
            ? updateRevision.updateRow(currentRevision.id, {
                apprevision: appId,
                name: "autosave",
                // @ts-ignore
                data: app,
                "revision-user": userId,
                updated_at: dayjs().toISOString(),
            })
            : insertRevision.insertRow({
                apprevision: appId,
                name: "autosave",
                // @ts-ignore
                data: app,
                "revision-user": userId,
            }));
        clean();
    })), [currentRevision]);
    React.useEffect(() => {
        if (isDirty) {
            autosave(user === null || user === void 0 ? void 0 : user.id, appId, app);
        }
    }, [isDirty, app, user, appId]);
    const saveAndClose = React.useCallback(() => __awaiter(this, void 0, void 0, function* () {
        if (!(user === null || user === void 0 ? void 0 : user.id))
            return;
        yield updateApp.updateRow(appId, {
            theme_color: app.theme.options.primaryColor,
        });
        useSave(appId, app, user, editorActions.setRevisionID, clean, insertRevision.insertRow);
    }), [
        editorActions,
        runtimeActions,
        insertRevision,
        app,
        onClose,
        user,
        updateApp,
        appId,
    ]);
    return (_jsx(_Fragment, { children: _jsx(Button, Object.assign({ size: "sm", variant: "outline", borderRadius: "4px", onClick: () => {
                saveAndClose();
            }, leftIcon: _jsx(Save, { fontSize: "16px" }), lineHeight: "0px", isDisabled: activeWindow === "settings" }, { children: insertRevision.status === "loading" ||
                updateRevision.status === "loading"
                ? "Saving"
                : "Save" })) }));
}
//# sourceMappingURL=SaveButton.js.map