"use strict";
/*---------------------------------------------------------------------------------------------
 * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
 * See LICENSE.md in the project root for license terms and full copyright notice.
 *--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
 * @module Frontstage
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSaveFrontstageSettings = void 0;
const React = require("react");
const useUiStateStorage_1 = require("../uistate/useUiStateStorage");
const Frontstage_1 = require("./Frontstage");
const lodash_1 = require("lodash");
/** @internal */
function useSaveFrontstageSettings(frontstageDef, store) {
    const uiSettingsStorage = (0, useUiStateStorage_1.useUiStateStorageHandler)();
    const saveSettingRef = React.useRef(undefined);
    const save = React.useCallback(async (frontstage, state) => {
        if (!saveSettingRef.current)
            return;
        if (state.draggedTab)
            return;
        return saveSettingRef.current(frontstage, state);
    }, []);
    React.useEffect(() => {
        const saveSetting = (saveSettingRef.current = (0, lodash_1.debounce)(async (frontstage, state) => {
            const id = frontstage.id;
            const setting = {
                id,
                version: frontstage.version,
                stateVersion: Frontstage_1.stateVersion,
                nineZone: (0, Frontstage_1.packNineZoneState)(state),
            };
            await uiSettingsStorage.saveSetting(Frontstage_1.FRONTSTAGE_SETTINGS_NAMESPACE, (0, Frontstage_1.getFrontstageStateSettingName)(id), setting);
        }, 1000));
        return () => {
            saveSettingRef.current = undefined;
            saveSetting.cancel();
        };
    }, [uiSettingsStorage]);
    React.useEffect(() => {
        return () => {
            // Save pending frontstage changes when changing frontstage.
            void saveSettingRef.current?.flush();
        };
    }, [frontstageDef]);
    React.useEffect(() => {
        return store.subscribe(() => {
            void save(frontstageDef, store.getState());
        });
    }, [save, frontstageDef, store]);
}
exports.useSaveFrontstageSettings = useSaveFrontstageSettings;
//# sourceMappingURL=useSaveFrontstageSettings.js.map