"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StateApiImpl = void 0;
const tslib_1 = require("tslib");
const AdaptableStore_1 = require("../../Redux/Store/AdaptableStore");
const ApiBase_1 = require("./ApiBase");
const Helper_1 = tslib_1.__importDefault(require("../../Utilities/Helpers/Helper"));
const AdaptableHelper_1 = require("../../Utilities/Helpers/AdaptableHelper");
const LayoutRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/LayoutRedux"));
const DashboardRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/DashboardRedux"));
const AlertRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/AlertRedux"));
const BulkUpdateRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/BulkUpdateRedux"));
const CalculatedColumnRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/CalculatedColumnRedux"));
const ChartingRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/ChartingRedux"));
const NoteRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/NoteRedux"));
const CustomSortRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/CustomSortRedux"));
const ExportRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/ExportRedux"));
const FormatColumnRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/FormatColumnRedux"));
const FreeTextColumnRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/FreeTextColumnRedux"));
const PlusMinusRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/PlusMinusRedux"));
const NamedQueryRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/NamedQueryRedux"));
const QuickSearchRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/QuickSearchRedux"));
const ScheduleRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/ScheduleRedux"));
const ShortcutRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/ShortcutRedux"));
const SystemStatusRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/SystemStatusRedux"));
const SmartEditRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/SmartEditRedux"));
const ThemeRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/ThemeRedux"));
const ToolPanelRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/ToolPanelRedux"));
const logDeprecation_1 = require("../../Utilities/logDeprecation");
class StateApiImpl extends ApiBase_1.ApiBase {
    configInit() {
        this.dispatchAction((0, AdaptableStore_1.InitState)());
    }
    copyAllStateToClipboard() {
        let state = this.getAdaptableState();
        let stringifiedState = JSON.stringify(state);
        Helper_1.default.copyToClipboard(stringifiedState);
    }
    copyUserStateToClipboard() {
        // This doesnt currently work...
        let state = this.getAdaptableState();
        //  let userState = state
        let stringifiedState = JSON.stringify(state);
        Helper_1.default.copyToClipboard(stringifiedState);
    }
    getPredefinedConfig() {
        (0, logDeprecation_1.logDeprecation)(this.getAdatableLogger(), 'StateApi', 'getPredefinedConfig', 'getInitialState');
        return this.getInitialState();
    }
    getInitialState() {
        return this._adaptable.adaptableOptions.initialState;
    }
    reloadPredefinedConfig(newPredefinedConfig) {
        (0, logDeprecation_1.logDeprecation)(this.getAdatableLogger(), 'StateApi', 'reloadPredefinedConfig', 'reloadInitialState');
        this.reloadInitialState(newPredefinedConfig);
    }
    reloadInitialState(newInitialState) {
        const adaptableOptions = this.getOptions();
        const oldState = this.getPersistedState();
        // clearing filters so that AG Grid doesnt display the filter icon in a column header after grid reloads
        // but this is a hack so would be nicer if there was a better way to do this
        this.getGridApi().clearFiltering();
        const clearStateFn = adaptableOptions.stateOptions?.clearState ||
            (() => {
                localStorage.removeItem(adaptableOptions.adaptableStateKey);
                return Promise.resolve(true);
            });
        this.getAdaptableStore()
            .saveStateNow(this._adaptable)
            .then(() => {
            const promise = clearStateFn({
                adaptableId: adaptableOptions.adaptableId,
                adaptableStateKey: adaptableOptions.adaptableStateKey,
                userName: adaptableOptions.userName,
            });
            promise.then(() => {
                this.setAdaptableStateKey(adaptableOptions.adaptableStateKey, {
                    initialState: newInitialState || adaptableOptions.initialState,
                    flushCurrentState: false,
                }).then(() => {
                    const newState = this.getPersistedState();
                    this.getEventApi().internalApi.fireAdaptableStateReloadedEvent(oldState, newState);
                });
            });
        });
    }
    getAllState() {
        return this.getAdaptableState();
    }
    getPersistedState() {
        // no assertion should be required here as soon as we make order in our state typings
        return this.getAdaptableStore().getCurrentStorageState();
    }
    getAllUserState() {
        return Object.values(this.getPersistedState());
    }
    loadUserState(state) {
        this.setAdaptableStateKey(this.getOptions().adaptableStateKey, {
            initialState: state || this.getOptions().initialState,
            flushCurrentState: false,
        });
    }
    getAdaptableSearchState() {
        const gridFilter = this.getGridFilterApi().getCurrentGridFilterExpression();
        const adaptableSearchState = {
            dataSet: this.getDataSetApi().getCurrentDataSet(),
            gridFilter: gridFilter,
            gridFilterAST: gridFilter ? this.getExpressionApi().getASTForExpression(gridFilter) : null,
            columnFilters: this.getColumnFilterApi().getColumnFilters(),
        };
        return adaptableSearchState;
    }
    getAdaptableSortState() {
        const adaptableSortState = {
            columnSorts: this.getGridApi().getColumnSorts(),
            customSorts: this.getCustomSortApi().getCustomSorts(),
        };
        return adaptableSortState;
    }
    getAdaptableOptions() {
        return undefined;
    }
    setAdaptableStateKey(adaptableStateKey, config) {
        return new Promise((resolve, reject) => {
            this.getAdaptableInternalApi().executeWithProgressIndicator(config?.progressIndicatorLabel ?? `Initialising...`, () => {
                const flushCurrentState = !config || config.flushCurrentState !== false;
                // make sure we persist any "pending" changes to state - since stateOptions.debounceStateDelay can cause
                // the state to be persisted with a delay, which we dont want in this case
                const flushStatePromise = flushCurrentState
                    ? this.getAdaptableStore().saveStateNow(this._adaptable)
                    : Promise.resolve(true);
                flushStatePromise.then(() => {
                    this.getOptions().adaptableStateKey = adaptableStateKey;
                    let initialState = config?.initialState;
                    if (initialState) {
                        initialState = (0, AdaptableHelper_1.addUuidsToInitialState)(initialState);
                    }
                    const promise = this.getAdaptableStore().loadStore({
                        adaptable: this._adaptable,
                        adaptableStateKey,
                        initialState: initialState,
                        postLoadHook: (state) => {
                            const agGridOptions = {
                                columnDefs: this._adaptable.agGridAdapter.getGridOption('columnDefs'),
                                autoGroupColumnDef: this._adaptable.agGridAdapter.getGridOption('autoGroupColumnDef'),
                                rowModelType: this._adaptable.agGridAdapter.getGridOption('rowModelType'),
                                treeData: this._adaptable.agGridAdapter.getGridOption('treeData'),
                            };
                            return this._adaptable.normalizeAdaptableState(state, agGridOptions);
                        },
                    });
                    promise
                        .then(() => {
                        this._adaptable.refreshLayout();
                    })
                        .then(() => {
                        // resolve main(result) promise
                        resolve();
                    }, (error) => {
                        // reject main(result) promise
                        reject(error);
                    })
                        .catch((e) => {
                        this.logError('Error setting Adaptable State Key', e);
                    })
                        .finally(() => {
                        this.getUserInterfaceApi().hideProgressIndicator();
                    });
                });
            });
        });
    }
    getDescriptionForModule(module) {
        return this._adaptable.ModuleService.getModuleInfoByModule(module).Description;
    }
    getHelpPageForModule(module) {
        return this._adaptable.ModuleService.getModuleInfoByModule(module).HelpPage;
    }
    getUserStateByStateKey(stateKey, returnJson = false) {
        switch (stateKey) {
            case 'Alert':
                return returnJson
                    ? JSON.stringify(this.getAdaptableState().Alert)
                    : this.getAdaptableState().Alert;
            case 'Application':
                return returnJson
                    ? JSON.stringify(this.getAdaptableState().Application)
                    : this.getAdaptableState().Application;
            case 'CalculatedColumn':
                return returnJson
                    ? JSON.stringify(this.getAdaptableState().CalculatedColumn)
                    : this.getAdaptableState().CalculatedColumn;
            case 'Charting':
                return returnJson
                    ? JSON.stringify(this.getAdaptableState().Charting)
                    : this.getAdaptableState().Charting;
            case 'Note':
                return returnJson
                    ? JSON.stringify(this.getAdaptableState().Note)
                    : this.getAdaptableState().Note;
            case 'CustomSort':
                return returnJson
                    ? JSON.stringify(this.getAdaptableState().CustomSort)
                    : this.getAdaptableState().CustomSort;
            case 'Dashboard':
                return returnJson
                    ? JSON.stringify(this.getAdaptableState().Dashboard)
                    : this.getAdaptableState().Dashboard;
            case 'Export':
                return returnJson
                    ? JSON.stringify(this.getAdaptableState().Export)
                    : this.getAdaptableState().Export;
            case 'FormatColumn':
                return returnJson
                    ? JSON.stringify(this.getAdaptableState().FormatColumn)
                    : this.getAdaptableState().FormatColumn;
            case 'FreeTextColumn':
                return returnJson
                    ? JSON.stringify(this.getAdaptableState().FreeTextColumn)
                    : this.getAdaptableState().FreeTextColumn;
            case 'Layout':
                return returnJson
                    ? JSON.stringify(this.getAdaptableState().Layout)
                    : this.getAdaptableState().Layout;
            case 'PlusMinus':
                return returnJson
                    ? JSON.stringify(this.getAdaptableState().PlusMinus)
                    : this.getAdaptableState().PlusMinus;
            case 'NamedQuery':
                return returnJson
                    ? JSON.stringify(this.getAdaptableState().NamedQuery)
                    : this.getAdaptableState().NamedQuery;
            case 'QuickSearch':
                return returnJson
                    ? JSON.stringify(this.getAdaptableState().QuickSearch)
                    : this.getAdaptableState().QuickSearch;
            case 'Schedule':
                return returnJson
                    ? JSON.stringify(this.getAdaptableState().Schedule)
                    : this.getAdaptableState().Schedule;
            case 'Shortcut':
                return returnJson
                    ? JSON.stringify(this.getAdaptableState().Shortcut)
                    : this.getAdaptableState().Shortcut;
            case 'Theme':
                return returnJson
                    ? JSON.stringify(this.getAdaptableState().Theme)
                    : this.getAdaptableState().Theme;
            case 'ToolPanel':
                return returnJson
                    ? JSON.stringify(this.getAdaptableState().ToolPanel)
                    : this.getAdaptableState().ToolPanel;
        }
    }
    incrementUserStateRevision(stateKey) {
        let state = this.getUserStateByStateKey(stateKey);
        if (typeof state.Revision === 'number') {
            state.Revision += 1;
        }
        else {
            state.Revision.Key += 1;
        }
        // need to save it...
    }
    getAlertState(returnJson = false) {
        return this.getUserStateByStateKey('Alert', returnJson);
    }
    getApplicationState(returnJson = false) {
        return this.getUserStateByStateKey('Application', returnJson);
    }
    getCalculatedColumnState(returnJson = false) {
        return this.getUserStateByStateKey('CalculatedColumn', returnJson);
    }
    getChartingState(returnJson = false) {
        return this.getUserStateByStateKey('Charting', returnJson);
    }
    getNoteState(returnJson = false) {
        return this.getUserStateByStateKey('Note', returnJson);
    }
    getCustomSortState(returnJson = false) {
        return this.getUserStateByStateKey('CustomSort', returnJson);
    }
    getDashboardState(returnJson = false) {
        return this.getUserStateByStateKey('Dashboard', returnJson);
    }
    getExportState(returnJson = false) {
        return this.getUserStateByStateKey('Export', returnJson);
    }
    getFreeTextColumnState(returnJson = false) {
        return this.getUserStateByStateKey('FreeTextColumn', returnJson);
    }
    getFormatColumnState(returnJson = false) {
        return this.getUserStateByStateKey('FormatColumn', returnJson);
    }
    getFlashingCellState(returnJson = false) {
        return this.getUserStateByStateKey('FlashingCell', returnJson);
    }
    getLayoutState(returnJson = false) {
        return this.getUserStateByStateKey('Layout', returnJson);
    }
    getPlusMinusState(returnJson = false) {
        return this.getUserStateByStateKey('PlusMinus', returnJson);
    }
    getNamedQueryState(returnJson = false) {
        return this.getUserStateByStateKey('NamedQuery', returnJson);
    }
    getQuickSearchState(returnJson = false) {
        return this.getUserStateByStateKey('QuickSearch', returnJson);
    }
    getScheduleState(returnJson = false) {
        return this.getUserStateByStateKey('Schedule', returnJson);
    }
    getShortcutState(returnJson = false) {
        return this.getUserStateByStateKey('Shortcut', returnJson);
    }
    getStatusBarState(returnJson = false) {
        return this.getUserStateByStateKey('StatusBar', returnJson);
    }
    getStyledColumnState(returnJson = false) {
        return this.getUserStateByStateKey('StyledColumn', returnJson);
    }
    getThemeState(returnJson = false) {
        return this.getUserStateByStateKey('Theme', returnJson);
    }
    getToolPanelState(returnJson = false) {
        return this.getUserStateByStateKey('ToolPanel', returnJson);
    }
    dispatchStateReadyAction(module) {
        switch (module) {
            case 'Alert':
                this.dispatchAction(AlertRedux.AlertReady(this.getAlertState()));
                break;
            case 'BulkUpdate':
                this.dispatchAction(BulkUpdateRedux.BulkUpdateReady());
                break;
            case 'CalculatedColumn':
                this.dispatchAction(CalculatedColumnRedux.CalculatedColumnReady(this.getCalculatedColumnState()));
                break;
            case 'Charting':
                this.dispatchAction(ChartingRedux.ChartingReady(this.getChartingState()));
                break;
            case 'Note':
                this.dispatchAction(NoteRedux.NoteReady(this.getNoteState()));
                break;
            case 'CustomSort':
                this.dispatchAction(CustomSortRedux.CustomSortReady(this.getCustomSortState()));
                break;
            case 'Dashboard':
                this.dispatchAction(DashboardRedux.DashboardReady(this.getDashboardState()));
                break;
            case 'Export':
                this.dispatchAction(ExportRedux.ExportReady(this.getExportState()));
                break;
            case 'FormatColumn':
                this.dispatchAction(FormatColumnRedux.FormatColumnReady(this.getFormatColumnState()));
                break;
            case 'FreeTextColumn':
                this.dispatchAction(FreeTextColumnRedux.FreeTextColumnReady(this.getFreeTextColumnState()));
                break;
            case 'Layout':
                this.dispatchAction(LayoutRedux.LayoutReady(this.getLayoutState()));
                break;
            case 'PlusMinus':
                this.dispatchAction(PlusMinusRedux.PlusMinusReady(this.getPlusMinusState()));
                break;
            case 'NamedQuery':
                this.dispatchAction(NamedQueryRedux.NamedQueryReady(this.getNamedQueryState()));
                break;
            case 'QuickSearch':
                this.dispatchAction(QuickSearchRedux.QuickSearchReady(this.getQuickSearchState()));
                break;
            case 'Schedule':
                this.dispatchAction(ScheduleRedux.ScheduleReady(this.getScheduleState()));
                break;
            case 'Shortcut':
                this.dispatchAction(ShortcutRedux.ShortcutReady(this.getShortcutState()));
                break;
            case 'SmartEdit':
                this.dispatchAction(SmartEditRedux.SmartEditReady());
                break;
            case 'SystemStatus':
                this.dispatchAction(SystemStatusRedux.SystemStatusReady());
                break;
            case 'Theme':
                this.dispatchAction(ThemeRedux.ThemeReady(this.getThemeState()));
                break;
            case 'ToolPanel':
                this.dispatchAction(ToolPanelRedux.ToolPanelReady(this.getToolPanelState()));
                break;
            case 'StatusBar':
                this.dispatchAction(ToolPanelRedux.ToolPanelReady(this.getToolPanelState()));
                break;
        }
    }
}
exports.StateApiImpl = StateApiImpl;
