"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createEngine = void 0;
const tslib_1 = require("tslib");
const debounce_1 = tslib_1.__importDefault(require("lodash/debounce"));
const AdaptableReduxMerger_1 = require("./AdaptableReduxMerger");
const AdaptableLogger_1 = require("../../agGrid/AdaptableLogger");
const buildAdaptableStateFunctionConfig_1 = require("./buildAdaptableStateFunctionConfig");
const checkStatus = (response) => {
    const error = new Error(response.statusText);
    if (response.status >= 200 && response.status < 300) {
        return response;
    }
    throw error;
};
const persistState = (state, config) => {
    return new Promise((resolve, reject) => {
        try {
            localStorage.setItem(config.adaptableStateKey, JSON.stringify(state));
            resolve();
        }
        catch (ex) {
            reject(ex);
        }
    });
};
const loadState = ({ adaptableId, adaptableStateKey }) => {
    const jsonState = localStorage.getItem(adaptableStateKey);
    const parsedJsonState = JSON.parse(jsonState) || {};
    return Promise.resolve(parsedJsonState);
};
class AdaptableReduxLocalStorageEngine {
    constructor(config) {
        this.adaptableId = config.adaptableId;
        this.adaptableStateKey = config.adaptableStateKey;
        this.userName = config.userName;
        this.initialState = config.initialState;
        this.loadState = config.loadState;
        this.persistState = config.persistState;
        this.save =
            config.debounceStateDelay > 0
                ? (0, debounce_1.default)(this.save, config.debounceStateDelay, {
                    maxWait: 1000,
                })
                : this.save;
    }
    setStateKey(adaptableStateKey) {
        this.adaptableStateKey = adaptableStateKey;
    }
    load(adaptableInstance, initialState = this.initialState) {
        return (this.loadState || loadState)((0, buildAdaptableStateFunctionConfig_1.buildAdaptableStateFunctionConfig)(adaptableInstance)).then((parsedJsonState) => {
            // we need to merge the Initial Adaptable State
            return Promise.resolve(initialState)
                .then((parsedInitialState) => {
                return (0, AdaptableReduxMerger_1.MergeStateFunction)(parsedInitialState, parsedJsonState);
            })
                .catch((err) => AdaptableLogger_1.AdaptableLogger.consoleErrorBase(`AdaptableId: ${this.adaptableId}`, err));
        });
    }
    save(adaptableInstance, state, actionName) {
        return this.saveNow(adaptableInstance, state, actionName);
    }
    saveNow(adaptableInstance, state, actionName) {
        const config = (0, buildAdaptableStateFunctionConfig_1.buildAdaptableStateFunctionConfig)(adaptableInstance);
        config.actionName = actionName;
        config.previousState = adaptableInstance.adaptableStore.getPreviousStorageState() || null;
        let stateObject = structuredClone(state);
        const getTransformedState = adaptableInstance.adaptableOptions.stateOptions.saveState;
        if (getTransformedState) {
            stateObject = getTransformedState(stateObject, config);
        }
        const promise = (this.persistState || persistState)(stateObject, config)?.catch(rejectWithMessage);
        if (!(promise instanceof Promise)) {
            AdaptableLogger_1.AdaptableLogger.consoleWarnBase(`AdaptableId: ${this.adaptableId}`, 'stateOptions.persistState should return a promise, it returned', 'Error', promise);
        }
        return promise;
    }
}
function rejectWithMessage(error) {
    return Promise.reject(error.message);
}
function createEngine(config) {
    return new AdaptableReduxLocalStorageEngine(config);
}
exports.createEngine = createEngine;
