"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VersionUpgrade17 = void 0;
const tslib_1 = require("tslib");
const VersionUpgrade_1 = require("./VersionUpgrade");
const ArrayExtensions_1 = tslib_1.__importDefault(require("../Utilities/Extensions/ArrayExtensions"));
const ObjectFactory_1 = tslib_1.__importDefault(require("../Utilities/ObjectFactory"));
const StringExtensions_1 = tslib_1.__importDefault(require("../Utilities/Extensions/StringExtensions"));
const updateSingleToMultiplePredicates_1 = require("../Utilities/updateSingleToMultiplePredicates");
class VersionUpgrade17 extends VersionUpgrade_1.VersionUpgrade {
    migrateState(state) {
        return this.migrateStateWithMethods(state, [
            this.migrateCalculatedColumnState,
            this.migrateAlertState,
            this.migrateToolPanelState,
            this.migrateStyledColumnState,
            this.migrateNamedQueryState,
            this.migrateGridFilterState,
            this.migrateFreeTextColumnState,
            this.migrateFormatColumnState,
            this.migrateFlashinCellState,
            this.migrateDashboardState,
            this.migrateColumnFilterState,
            this.migrateChartingState,
        ]);
    }
    migrateChartingState(state) {
        // const allChartDefinitions = this.api.chartingApi.getChartDefinitions();
        const allChartDefinitions = state.Charting?.ChartDefinitions;
        if (Array.isArray(allChartDefinitions)) {
            allChartDefinitions
                .filter((chartDefinition) => 'model' in chartDefinition || !('Name' in chartDefinition))
                .forEach((charDefinition) => {
                if ('model' in charDefinition) {
                    charDefinition.Model = charDefinition.model;
                    delete charDefinition.model;
                }
                if (!('Name' in charDefinition)) {
                    // default to chartId
                    // @ts-ignore possible because First iteration had no 'Name' and model was under 'model' key (lowercase)
                    charDefinition.Name = charDefinition.Model.chartId;
                }
            });
        }
        return state;
    }
    migrateColumnFilterState(state) {
        // Update Module Buttons
        const moduleButtons = state.Dashboard?.ModuleButtons;
        if (moduleButtons?.length && !moduleButtons.includes('ColumnFilter')) {
            const dashboardState = state.Dashboard ?? {};
            dashboardState.ModuleButtons = moduleButtons.map((moduleButton) => {
                if (moduleButton == 'Filter') {
                    return 'ColumnFilter';
                }
                return moduleButton;
            });
        }
        // Update Toolbars
        const tabs = state.Dashboard?.Tabs;
        if (Array.isArray(tabs)) {
            state.Dashboard.Tabs = tabs.map((tab) => {
                if (tab.Toolbars.includes('Filter') &&
                    !tab.Toolbars.includes('ColumnFilter')) {
                    return {
                        ...tab,
                        // replace with 'GridFilter'
                        Toolbars: tab.Toolbars.map((t) => (t == 'Filter' ? 'ColumnFilter' : t)),
                    };
                }
                return tab;
            });
        }
        // - move pinned toolbars
        const pinnedToolbars = state.Dashboard?.PinnedToolbars;
        if (pinnedToolbars && !pinnedToolbars?.includes('ColumnFilter')) {
            state.Dashboard.PinnedToolbars = pinnedToolbars.map((pinnedToolbar) => {
                if (pinnedToolbar == 'Filter') {
                    return 'ColumnFilter';
                }
                return pinnedToolbar;
            });
        }
        // Update Status Bar
        const statusBars = state.StatusBar?.StatusBars;
        if (statusBars) {
            state.StatusBar.StatusBars = statusBars.map((panel) => {
                return {
                    ...panel,
                    StatusBarPanels: panel.StatusBarPanels.map((panel) => {
                        if (panel === 'Filter') {
                            return 'ColumnFilter';
                        }
                        return panel;
                    }),
                };
            });
        }
        return state;
    }
    migrateDashboardState(state) {
        // let dashboardState: any = this.api.dashboardApi.getDashboardState();
        let dashboardState = state.Dashboard;
        if (dashboardState?.VisibleButtons) {
            this.logger.warn(`Migrating deprecated DashboardState.VisibleButtons: [${dashboardState.VisibleButtons}].`);
            state.Dashboard.ModuleButtons = [
                ...state.Dashboard.ModuleButtons,
                ...dashboardState.VisibleButtons,
            ];
            //@ts-ignore delete as no longer needed
            delete state.Dashboard.VisibleButtons;
        }
        return state;
    }
    migrateFlashinCellState(state) {
        const flashingCellState = state.FlashingCell;
        if (Array.isArray(flashingCellState?.FlashingCellDefinitions)) {
            flashingCellState.FlashingCellDefinitions.forEach((flashingCellDefinition) => {
                if (flashingCellDefinition.Rule && 'Predicate' in flashingCellDefinition.Rule) {
                    (0, updateSingleToMultiplePredicates_1.updateSingleToMultiplePredicates)(flashingCellDefinition.Rule);
                }
            });
        }
        return state;
    }
    migrateFormatColumnState(state) {
        // const formatColumns = this.api.formatColumnApi.getFormatColumns();
        const formatColumns = state.FormatColumn?.FormatColumns || [];
        formatColumns.forEach((formatColumn) => {
            if (formatColumn.Rule && 'Predicate' in formatColumn.Rule) {
                //@ts-ignore ignore
                (0, updateSingleToMultiplePredicates_1.updateSingleToMultiplePredicates)(formatColumn.Rule);
            }
        });
        // update ConditionalStyle StatusBarPanel
        // const oldStatusBars = this.api.internalApi.getState().StatusBar.StatusBars;
        const statusBars = state.StatusBar?.StatusBars || [];
        let replaceConditionalStyleStatusBar = false;
        statusBars.forEach((statusBar) => ({
            ...statusBar,
            StatusBarPanels: [
                ...new Set(statusBar.StatusBarPanels.map((statusBarPanel) => {
                    if (statusBarPanel === 'ConditionalStyle') {
                        replaceConditionalStyleStatusBar = true;
                        return 'FormatColumn';
                    }
                    return statusBarPanel;
                })),
            ],
        }));
        // update ConditionalStyle dashboard buttons
        // const dashboardModuleButtons = this.api.internalApi.getState().Dashboard.ModuleButtons as any;
        const dashboardModuleButtons = state.Dashboard?.ModuleButtons;
        if (dashboardModuleButtons && dashboardModuleButtons.includes('ConditionalStyle')) {
            dashboardModuleButtons[dashboardModuleButtons.indexOf('ConditionalStyle')] = 'FormatColumn';
        }
        // update ConditionalStyle toolPanel buttons
        // const toolPanelModuleButtons = this.api.internalApi.getState().ToolPanel.ModuleButtons as any;
        const toolPanelModuleButtons = state.ToolPanel?.ModuleButtons;
        if (toolPanelModuleButtons && toolPanelModuleButtons.includes('ConditionalStyle')) {
            toolPanelModuleButtons[toolPanelModuleButtons.indexOf('ConditionalStyle')] = 'FormatColumn';
        }
        return state;
    }
    migrateFreeTextColumnState(state) {
        // make sure all default to type string
        const allFreeTextColumns = state.FreeTextColumn?.FreeTextColumns || [];
        for (const freeTextColumn of allFreeTextColumns) {
            const unTypedCol = freeTextColumn;
            if (unTypedCol.DataType) {
                const dataType = unTypedCol.DataType;
                delete unTypedCol['DataType'];
                if (!freeTextColumn.FreeTextColumnSettings) {
                    freeTextColumn.FreeTextColumnSettings = {
                        DataType: dataType,
                    };
                }
                else {
                    freeTextColumn.FreeTextColumnSettings.DataType = dataType;
                }
            }
            if (!freeTextColumn.FreeTextColumnSettings) {
                freeTextColumn.FreeTextColumnSettings = {
                    DataType: 'String',
                };
            }
            if (!freeTextColumn.FreeTextColumnSettings.DataType) {
                freeTextColumn.FreeTextColumnSettings.DataType = 'String';
            }
        }
        return state;
    }
    migrateGridFilterState(state) {
        const oldQueryState = state.Query;
        if (!oldQueryState) {
            return state;
        }
        // - move query to current layout
        const expression = oldQueryState.CurrentQuery;
        const currentLayout = state.Layout.Layouts?.find((l) => l.Name === state.Layout.CurrentLayout);
        const currentGridFilter = currentLayout?.GridFilter;
        const currentGridFilterExpression = currentGridFilter && !currentGridFilter.IsSuspended ? currentGridFilter.Expression || '' : '';
        if (expression && StringExtensions_1.default.IsNullOrEmpty(currentGridFilterExpression)) {
            currentLayout.GridFilter = {
                ...currentGridFilter,
                Expression: expression,
            };
        }
        // - move dashboard/toolbar
        state.Dashboard.Tabs?.forEach((tab) => {
            if (tab.Toolbars.includes('Query')) {
                tab.Toolbars = tab.Toolbars.map((t) => (t == 'Query' ? 'GridFilter' : t));
            }
        });
        // - move pinned toolbars
        let updatePinnedToolbars = false;
        if (state.Dashboard.PinnedToolbars) {
            state.Dashboard.PinnedToolbars = state.Dashboard.PinnedToolbars.map((pinnedToolbar) => {
                if (pinnedToolbar == 'Query') {
                    return 'GridFilter';
                }
                return pinnedToolbar;
            });
        }
        return state;
    }
    migrateNamedQueryState(state) {
        // - move named queries from old Query State to this Module
        // Note: GridFilter Module moves the "old" CurrentQuery into Layout
        // const oldQueryState: QueryState = this.api.internalApi.getAdaptableState().Query;
        const oldQueryState = state.Query;
        const oldNamedQueries = oldQueryState?.NamedQueries;
        if (ArrayExtensions_1.default.IsNotNullOrEmpty(oldNamedQueries)) {
            const currentNamedQueries = state.NamedQuery.NamedQueries;
            oldNamedQueries.forEach((oldNamedQuery) => {
                const currentQuery = currentNamedQueries.find((q) => q.Name === oldNamedQuery.Name);
                if (!currentQuery) {
                    state.NamedQuery?.NamedQueries?.push(oldNamedQuery);
                }
            });
        }
        if (oldQueryState) {
            delete state.Query;
        }
        return state;
    }
    migrateStyledColumnState(state) {
        const formatColumnsWithColumnStyles = state.FormatColumn?.FormatColumns?.filter((fc) => fc.ColumnStyle) || [];
        if (!formatColumnsWithColumnStyles.length) {
            return state;
        }
        this.logger.info(`Migrating ${formatColumnsWithColumnStyles.length} FormatColumn styles to StyledColumns.`, formatColumnsWithColumnStyles);
        // delete the format columns with column styles
        state.FormatColumn.FormatColumns = state.FormatColumn.FormatColumns?.filter((fc) => !fc.ColumnStyle);
        const styledColumns = formatColumnsWithColumnStyles
            .map((formatColumn) => {
            if (!('ColumnIds' in formatColumn.Scope)) {
                return null;
            }
            return {
                ...ObjectFactory_1.default.CreateEmptyStyledColumn(),
                ColumnId: formatColumn.Scope.ColumnIds[0],
                ...formatColumn.ColumnStyle,
            };
        })
            .filter(Boolean);
        state.StyledColumn.StyledColumns ??= [];
        styledColumns.forEach((styledColumn) => {
            state.StyledColumn.StyledColumns.push(styledColumn);
        });
        return state;
    }
    migrateToolPanelState(state) {
        // const deprecatedToolPanelConfigs: AdaptableToolPanels | undefined = (
        //   this.api.toolPanelApi.getToolPanelState() as any
        // ).VisibleToolPanels;
        const deprecatedToolPanelConfigs = state.ToolPanel
            ?.VisibleToolPanels;
        if (deprecatedToolPanelConfigs?.length) {
            this.logger.warn(`Migrating deprecated ToolPanelState.VisibleToolPanels: [${deprecatedToolPanelConfigs}].`);
            const migratedToolPanelConfigs = deprecatedToolPanelConfigs.map((toolPanel) => ({
                Name: toolPanel,
                State: 'collapsed',
            }));
            state.ToolPanel.ToolPanels = migratedToolPanelConfigs;
        }
        return state;
    }
    migrateAlertState(state) {
        state.Alert?.AlertDefinitions?.forEach((alertDefinition) => {
            if (alertDefinition.Rule && 'Predicate' in alertDefinition.Rule) {
                (0, updateSingleToMultiplePredicates_1.updateSingleToMultiplePredicates)(alertDefinition.Rule);
            }
        });
        const alertState = state.Alert;
        if (ArrayExtensions_1.default.IsEmpty(state.FlashingCell?.FlashingCellDefinitions) &&
            ArrayExtensions_1.default.IsNotNullOrEmpty(alertState?.FlashingAlertDefinitions)) {
            state.FlashingCell.FlashingCellDefinitions = alertState.FlashingAlertDefinitions;
            //@ts-ignore delete as no longer needed
            delete state.Alert.FlashingAlertDefinitions;
        }
        state.Alert?.AlertDefinitions?.forEach((alertDefinition) => {
            // if ShowPopup then change to DisplayNotificate
            if (alertDefinition.AlertProperties &&
                alertDefinition.AlertProperties.ShowPopup &&
                alertDefinition.AlertProperties.ShowPopup == true &&
                !alertDefinition.AlertProperties.DisplayNotification) {
                alertDefinition.AlertProperties.DisplayNotification = true;
                alertDefinition.AlertProperties.ShowPopup = undefined;
            }
            // if no rule but a predicate then use that
            if (!alertDefinition.Rule) {
                if (alertDefinition.Predicate && alertDefinition.Predicate != undefined) {
                    const predicate = alertDefinition.Predicate;
                    alertDefinition.Rule = {
                        Predicate: predicate,
                    };
                    alertDefinition.Predicate = undefined;
                }
            }
            else {
                //migrate alert definitions with `AggregationExpression` (now `AggregatedBooleanExpression`)
                const obsoleteAggregationExpression = alertDefinition.Rule['AggregationExpression'];
                if (obsoleteAggregationExpression) {
                    alertDefinition.Rule.AggregatedBooleanExpression = obsoleteAggregationExpression;
                }
            }
        });
        return state;
    }
    migrateCalculatedColumnState(state) {
        state.CalculatedColumn?.CalculatedColumns?.forEach((cc) => {
            if (cc.ColumnExpression && !cc.Query) {
                cc.Query = {
                    ScalarExpression: cc.ColumnExpression,
                };
                cc.ColumnExpression = undefined;
            }
            if (!cc.CalculatedColumnSettings) {
                cc.CalculatedColumnSettings = {
                    DataType: 'number',
                };
                this.logger.warn(`Migrating Calculated Column "${cc.ColumnId}": adding default CalculatedColumnSettings.`);
            }
        });
        return state;
    }
    migrateUserState(state) {
        return state;
    }
}
exports.VersionUpgrade17 = VersionUpgrade17;
