"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isPivotLayout = exports.pivotLayoutModelToPivotLayout = exports.tableLayoutModelToTableLayout = exports.pivotLayoutToPivotLayoutModel = exports.tableLayoutToTableLayoutModel = exports.checkForDuplicateColumns = exports.toRowGroupValuesForLayoutModel = exports.toRowGroupValuesForLayoutState = exports.getLayoutRowGroupValuesExceptionGroupKeys = exports.normalizePivotLayout = exports.normalizeTableLayout = exports.normalizeLayout = exports.areLayoutsEqual = exports.layoutModelToLayoutState = exports.layoutStateToLayoutModel = void 0;
const tslib_1 = require("tslib");
const isEqual_1 = tslib_1.__importDefault(require("lodash/isEqual"));
const isPivotLayoutModel_1 = require("../../layout-manager/src/isPivotLayoutModel");
const normalizeLayoutModel_1 = require("../../layout-manager/src/normalizeLayoutModel");
const simplifyLayoutModel_1 = require("../../layout-manager/src/simplifyLayoutModel");
const AggregationColumns_1 = require("../../AdaptableState/Common/AggregationColumns");
const AdaptableHelper_1 = require("../../Utilities/Helpers/AdaptableHelper");
const layoutStateToLayoutModel = (layout) => {
    if ((0, exports.isPivotLayout)(layout)) {
        return (0, exports.pivotLayoutToPivotLayoutModel)(layout);
    }
    return (0, exports.tableLayoutToTableLayoutModel)(layout);
};
exports.layoutStateToLayoutModel = layoutStateToLayoutModel;
const layoutModelToLayoutState = (layoutModel) => {
    if ((0, isPivotLayoutModel_1.isPivotLayoutModel)(layoutModel)) {
        return (0, exports.pivotLayoutModelToPivotLayout)(layoutModel);
    }
    return (0, exports.tableLayoutModelToTableLayout)(layoutModel);
};
exports.layoutModelToLayoutState = layoutModelToLayoutState;
function cleanupAdaptableObjectPrimitives(layout) {
    const l = layout;
    for (const key in l) {
        if (typeof l[key] === 'object') {
            (0, AdaptableHelper_1.removeAdaptableObjectPrimitivesInlineDeep)(l[key]);
        }
    }
}
/**
 * Compares 2 Layouts for equality
 * @param layout1 First Layout
 * @param layout2 Second Layout
 */
const areLayoutsEqual = (layout1, layout2) => {
    if (!layout1 && !layout2) {
        return true;
    }
    if (!layout1 || !layout2) {
        return false;
    }
    return (0, isEqual_1.default)((0, exports.normalizeLayout)(layout1), (0, exports.normalizeLayout)(layout2));
};
exports.areLayoutsEqual = areLayoutsEqual;
const normalizeLayout = (layout, options) => {
    if ((0, exports.isPivotLayout)(layout)) {
        return (0, exports.normalizePivotLayout)(layout);
    }
    return (0, exports.normalizeTableLayout)(layout, options);
};
exports.normalizeLayout = normalizeLayout;
const normalizeTableLayout = (tableLayout, options) => {
    let model = (0, exports.tableLayoutToTableLayoutModel)(tableLayout);
    model = (0, normalizeLayoutModel_1.normalizeTableLayoutModel)(model, options);
    tableLayout = (0, exports.tableLayoutModelToTableLayout)(model);
    return tableLayout;
};
exports.normalizeTableLayout = normalizeTableLayout;
const normalizePivotLayout = (pivotLayout) => {
    let model = (0, exports.pivotLayoutToPivotLayoutModel)(pivotLayout);
    model = (0, normalizeLayoutModel_1.normalizePivotLayoutModel)(model);
    pivotLayout = (0, exports.pivotLayoutModelToPivotLayout)(model);
    return pivotLayout;
};
exports.normalizePivotLayout = normalizePivotLayout;
const errorOnceMessages = new Map();
const errorOnce = (message) => {
    if (errorOnceMessages.get(message)) {
        return;
    }
    console.error(message);
    errorOnceMessages.set(message, true);
};
const getLayoutRowGroupValuesExceptionGroupKeys = (layout) => {
    if (!layout.RowGroupValues) {
        return [];
    }
    if (layout.RowGroupValues?.RowGroupDefaultBehavior === 'always-collapsed') {
        return [];
    }
    if (layout.RowGroupValues?.RowGroupDefaultBehavior === 'always-expanded') {
        return [];
    }
    if (Array.isArray(layout.RowGroupValues?.GroupKeys)) {
        const currentGroupedColumns = (layout.RowGroupedColumns || []).join(',');
        const matchingGroupKeys = layout.RowGroupValues.GroupKeys.find(({ RowGroupedColumns }) => {
            return RowGroupedColumns.join(',') === currentGroupedColumns;
        });
        if (matchingGroupKeys) {
            return matchingGroupKeys.ExceptionGroupKeys;
        }
    }
    return layout.RowGroupValues.ExceptionGroupKeys || [];
};
exports.getLayoutRowGroupValuesExceptionGroupKeys = getLayoutRowGroupValuesExceptionGroupKeys;
const toRowGroupValuesForLayoutState = (rowGroupValuesModel) => {
    if (!rowGroupValuesModel) {
        return undefined;
    }
    const rowGroupValuesState = {
        RowGroupDefaultBehavior: rowGroupValuesModel.RowGroupDisplay,
    };
    if (rowGroupValuesModel.RowGroupDisplay === 'collapsed' ||
        rowGroupValuesModel.RowGroupDisplay === 'expanded') {
        if (rowGroupValuesModel.GroupKeys) {
            rowGroupValuesState.GroupKeys =
                rowGroupValuesModel.GroupKeys.map(({ RowGroupedColumns, Values }) => {
                    return {
                        RowGroupedColumns,
                        ExceptionGroupKeys: Values,
                    };
                });
        }
        else {
            rowGroupValuesState.ExceptionGroupKeys =
                rowGroupValuesModel.Values;
        }
    }
    return rowGroupValuesState;
};
exports.toRowGroupValuesForLayoutState = toRowGroupValuesForLayoutState;
const toRowGroupValuesForLayoutModel = (rowGroupValuesState) => {
    if (!rowGroupValuesState) {
        return undefined;
    }
    if (rowGroupValuesState.RowGroupDefaultBehavior === 'always-collapsed' ||
        rowGroupValuesState.RowGroupDefaultBehavior === 'always-expanded') {
        return {
            RowGroupDisplay: rowGroupValuesState.RowGroupDefaultBehavior,
        };
    }
    if (rowGroupValuesState.GroupKeys) {
        return {
            RowGroupDisplay: rowGroupValuesState.RowGroupDefaultBehavior,
            GroupKeys: rowGroupValuesState.GroupKeys.map(({ RowGroupedColumns, ExceptionGroupKeys }) => {
                return {
                    RowGroupedColumns,
                    Values: ExceptionGroupKeys,
                };
            }),
        };
    }
    return {
        RowGroupDisplay: rowGroupValuesState.RowGroupDefaultBehavior,
        Values: rowGroupValuesState.ExceptionGroupKeys || [],
    };
};
exports.toRowGroupValuesForLayoutModel = toRowGroupValuesForLayoutModel;
const checkForDuplicateColumns = (layout) => {
    if (layout.TableColumns) {
        const set = new Set(layout.TableColumns);
        if (set.size !== layout.TableColumns.length) {
            layout.TableColumns.reduce((acc, col) => {
                acc[col] = (acc[col] || 0) + 1;
                if (acc[col] > 1) {
                    // if you change this message, make sure you also update the associated test error-on-duplicate-column.spec.ts
                    errorOnce(`Duplicate column "${col}" in layout "${layout.Name}"!`);
                }
                return acc;
            }, {});
        }
    }
};
exports.checkForDuplicateColumns = checkForDuplicateColumns;
const tableLayoutToTableLayoutModel = (tableLayout) => {
    tableLayout = structuredClone(tableLayout);
    cleanupAdaptableObjectPrimitives(tableLayout);
    const TableAggregationColumns = (tableLayout.TableAggregationColumns || []).map(({ ColumnId, AggFunc }) => {
        return {
            ColumnId,
            AggFunc: toAggFunc(AggFunc),
        };
    });
    const result = (0, simplifyLayoutModel_1.simplifyTableLayoutModel)({
        Ignore_Name: tableLayout.Name,
        SuppressAggFuncInHeader: tableLayout.SuppressAggFuncInHeader,
        TableColumns: tableLayout.TableColumns,
        ColumnWidths: tableLayout.ColumnWidths,
        ColumnVisibility: tableLayout.ColumnVisibility,
        ColumnSorts: tableLayout.ColumnSorts,
        RowGroupedColumns: tableLayout.RowGroupedColumns,
        ColumnPinning: tableLayout.ColumnPinning,
        RowGroupValues: (0, exports.toRowGroupValuesForLayoutModel)(tableLayout.RowGroupValues),
        ColumnGroupValues: tableLayout.ColumnGroupValues
            ? tableLayout.ColumnGroupValues.ColumnGroupDefaultBehavior === 'always-expanded' ||
                tableLayout.ColumnGroupValues.ColumnGroupDefaultBehavior === 'always-collapsed'
                ? {
                    ColumnGroupDisplay: tableLayout.ColumnGroupValues.ColumnGroupDefaultBehavior,
                }
                : {
                    ColumnGroupDisplay: tableLayout.ColumnGroupValues.ColumnGroupDefaultBehavior,
                    Values: tableLayout.ColumnGroupValues.ExceptionGroupKeys || [],
                }
            : undefined,
        TableAggregationColumns: TableAggregationColumns,
        GrandTotalRow: tableLayout.GrandTotalRow,
    });
    if (tableLayout.RowGroupDisplayType) {
        result.RowGroupDisplayType = tableLayout.RowGroupDisplayType;
    }
    if (tableLayout.ColumnFilters) {
        result.Ignore_ColumnFilters = tableLayout.ColumnFilters;
    }
    if (tableLayout.GridFilter) {
        result.Ignore_GridFilter = tableLayout.GridFilter;
    }
    if (tableLayout.ColumnHeaders) {
        result.Ignore_ColumnHeaders = tableLayout.ColumnHeaders;
    }
    if (tableLayout.AutoSizeColumns != null) {
        result.Ignore_AutoSizeColumns = tableLayout.AutoSizeColumns;
    }
    if (tableLayout.IsReadOnly != null) {
        result.Ignore_IsReadOnly = tableLayout.IsReadOnly;
    }
    if (tableLayout.Tags) {
        result.Ignore_Tags = tableLayout.Tags;
    }
    if (tableLayout.Source) {
        result.Ignore_Source = tableLayout.Source;
    }
    if (tableLayout.AdaptableVersion) {
        result.Ignore_AdaptableVersion = tableLayout.AdaptableVersion;
    }
    if (tableLayout.Uuid) {
        result.Ignore_Uuid = tableLayout.Uuid;
    }
    if (tableLayout.RowSummaries != null) {
        result.Ignore_RowSummaries = tableLayout.RowSummaries;
    }
    return result;
};
exports.tableLayoutToTableLayoutModel = tableLayoutToTableLayoutModel;
const pivotLayoutToPivotLayoutModel = (pivotLayout) => {
    pivotLayout = structuredClone(pivotLayout);
    cleanupAdaptableObjectPrimitives(pivotLayout);
    const result = (0, simplifyLayoutModel_1.simplifyPivotLayoutModel)({
        Ignore_Name: pivotLayout.Name,
        SuppressAggFuncInHeader: pivotLayout.SuppressAggFuncInHeader,
        ColumnWidths: pivotLayout.ColumnWidths,
        ColumnVisibility: pivotLayout.ColumnVisibility,
        ColumnSorts: pivotLayout.ColumnSorts,
        PivotGroupedColumns: pivotLayout.PivotGroupedColumns,
        ColumnPinning: pivotLayout.ColumnPinning,
        PivotColumns: pivotLayout.PivotColumns,
        PivotExpandLevel: pivotLayout.PivotExpandLevel,
        PivotAggregationColumns: (pivotLayout.PivotAggregationColumns || []).map(({ ColumnId, AggFunc, Total }) => {
            return {
                ColumnId,
                AggFunc: toAggFunc(AggFunc),
                Total,
            };
        }),
        GrandTotalRow: pivotLayout.GrandTotalRow,
        PivotGrandTotal: pivotLayout.PivotGrandTotal,
        PivotColumnTotal: pivotLayout.PivotColumnTotal,
        RowGroupValues: (0, exports.toRowGroupValuesForLayoutModel)(pivotLayout.RowGroupValues),
        ColumnGroupValues: pivotLayout.ColumnGroupValues
            ? pivotLayout.ColumnGroupValues.ColumnGroupDefaultBehavior === 'always-expanded' ||
                pivotLayout.ColumnGroupValues.ColumnGroupDefaultBehavior === 'always-collapsed'
                ? {
                    ColumnGroupDisplay: pivotLayout.ColumnGroupValues.ColumnGroupDefaultBehavior,
                }
                : {
                    ColumnGroupDisplay: pivotLayout.ColumnGroupValues.ColumnGroupDefaultBehavior,
                    Values: pivotLayout.ColumnGroupValues.ExceptionGroupKeys || [],
                }
            : undefined,
    });
    if (pivotLayout.ColumnFilters) {
        result.Ignore_ColumnFilters = pivotLayout.ColumnFilters;
    }
    if (pivotLayout.GridFilter) {
        result.Ignore_GridFilter = pivotLayout.GridFilter;
    }
    if (pivotLayout.ColumnHeaders) {
        result.Ignore_ColumnHeaders = pivotLayout.ColumnHeaders;
    }
    if (pivotLayout.IsReadOnly != null) {
        result.Ignore_IsReadOnly = pivotLayout.IsReadOnly;
    }
    if (pivotLayout.Tags) {
        result.Ignore_Tags = pivotLayout.Tags;
    }
    if (pivotLayout.AutoSizeColumns != null) {
        result.Ignore_AutoSizeColumns = pivotLayout.AutoSizeColumns;
    }
    if (pivotLayout.Source) {
        result.Ignore_Source = pivotLayout.Source;
    }
    if (pivotLayout.AdaptableVersion) {
        result.Ignore_AdaptableVersion = pivotLayout.AdaptableVersion;
    }
    if (pivotLayout.Uuid) {
        result.Ignore_Uuid = pivotLayout.Uuid;
    }
    return result;
};
exports.pivotLayoutToPivotLayoutModel = pivotLayoutToPivotLayoutModel;
function toAggFunc(aggFunc) {
    if ((0, AggregationColumns_1.isWeightedAverageAggregation)(aggFunc)) {
        return { aggFunc: AggregationColumns_1.WEIGHTED_AVERAGE_AGG_FN_NAME, weightedColumnId: aggFunc.weightedColumnId };
    }
    return { aggFunc };
}
const tableLayoutModelToTableLayout = (layoutModel) => {
    const tableLayout = {
        Name: layoutModel.Ignore_Name,
        TableColumns: layoutModel.TableColumns,
        ColumnWidths: layoutModel.ColumnWidths,
        ColumnVisibility: layoutModel.ColumnVisibility,
        ColumnSorts: layoutModel.ColumnSorts,
    };
    if (layoutModel.SuppressAggFuncInHeader) {
        tableLayout.SuppressAggFuncInHeader = layoutModel.SuppressAggFuncInHeader;
    }
    if (layoutModel.Ignore_GridFilter) {
        tableLayout.GridFilter = layoutModel.Ignore_GridFilter;
    }
    if (layoutModel.Ignore_ColumnFilters) {
        tableLayout.ColumnFilters = layoutModel.Ignore_ColumnFilters;
    }
    if (layoutModel.Ignore_ColumnHeaders) {
        tableLayout.ColumnHeaders = layoutModel.Ignore_ColumnHeaders;
    }
    if (layoutModel.Ignore_AutoSizeColumns != null) {
        tableLayout.AutoSizeColumns = layoutModel.Ignore_AutoSizeColumns;
    }
    if (layoutModel.Ignore_RowSummaries) {
        tableLayout.RowSummaries = layoutModel.Ignore_RowSummaries;
    }
    if (layoutModel.Ignore_IsReadOnly != null) {
        tableLayout.IsReadOnly = layoutModel.Ignore_IsReadOnly;
    }
    if (layoutModel.Ignore_Tags) {
        tableLayout.Tags = layoutModel.Ignore_Tags;
    }
    if (layoutModel.Ignore_Source) {
        tableLayout.Source = layoutModel.Ignore_Source;
    }
    if (layoutModel.Ignore_AdaptableVersion) {
        tableLayout.AdaptableVersion = layoutModel.Ignore_AdaptableVersion;
    }
    if (layoutModel.Ignore_Uuid) {
        tableLayout.Uuid = layoutModel.Ignore_Uuid;
    }
    if (layoutModel.RowGroupDisplayType) {
        tableLayout.RowGroupDisplayType = layoutModel.RowGroupDisplayType;
    }
    if (layoutModel.RowGroupedColumns) {
        tableLayout.RowGroupedColumns = layoutModel.RowGroupedColumns;
    }
    else {
        delete tableLayout.RowGroupedColumns;
    }
    if (layoutModel.ColumnPinning) {
        tableLayout.ColumnPinning = layoutModel.ColumnPinning;
    }
    else {
        delete tableLayout.ColumnPinning;
    }
    if (layoutModel.RowGroupValues) {
        tableLayout.RowGroupValues = (0, exports.toRowGroupValuesForLayoutState)(layoutModel.RowGroupValues);
    }
    else {
        delete tableLayout.RowGroupValues;
    }
    if (layoutModel.ColumnGroupValues) {
        tableLayout.ColumnGroupValues = {
            ColumnGroupDefaultBehavior: layoutModel.ColumnGroupValues.ColumnGroupDisplay,
        };
        if ((layoutModel.ColumnGroupValues.ColumnGroupDisplay === 'collapsed' ||
            layoutModel.ColumnGroupValues.ColumnGroupDisplay === 'expanded') &&
            layoutModel.ColumnGroupValues.Values) {
            // @ts-ignore
            tableLayout.ColumnGroupValues.ExceptionGroupKeys = layoutModel.ColumnGroupValues.Values;
        }
    }
    if (layoutModel.TableAggregationColumns) {
        tableLayout.TableAggregationColumns = layoutModel.TableAggregationColumns.map(({ ColumnId, AggFunc }) => {
            return {
                ColumnId,
                AggFunc: toAggregationColumnValue(AggFunc),
            };
        });
    }
    else {
        delete tableLayout.TableAggregationColumns;
    }
    if (layoutModel.GrandTotalRow) {
        tableLayout.GrandTotalRow = layoutModel.GrandTotalRow;
    }
    else {
        delete tableLayout.GrandTotalRow;
    }
    cleanupAdaptableObjectPrimitives(tableLayout);
    return tableLayout;
};
exports.tableLayoutModelToTableLayout = tableLayoutModelToTableLayout;
function toAggregationColumnValue(columnAggregationModel) {
    return columnAggregationModel &&
        typeof columnAggregationModel.aggFunc === 'string' &&
        (0, AggregationColumns_1.isWeightedAverageAggFuncName)(columnAggregationModel.aggFunc)
        ? {
            type: 'weightedAverage',
            weightedColumnId: columnAggregationModel.weightedColumnId,
        }
        : columnAggregationModel.aggFunc;
}
const pivotLayoutModelToPivotLayout = (layoutModel) => {
    const pivotLayout = {
        Name: layoutModel.Ignore_Name,
        PivotColumns: layoutModel.PivotColumns,
        TableColumns: layoutModel.TableColumns,
        ColumnWidths: layoutModel.ColumnWidths,
        ColumnVisibility: layoutModel.ColumnVisibility,
        ColumnSorts: layoutModel.ColumnSorts,
        ColumnPinning: layoutModel.ColumnPinning,
        PivotExpandLevel: layoutModel.PivotExpandLevel,
    };
    if (layoutModel.SuppressAggFuncInHeader) {
        pivotLayout.SuppressAggFuncInHeader = layoutModel.SuppressAggFuncInHeader;
    }
    if (layoutModel.Ignore_GridFilter) {
        pivotLayout.GridFilter = layoutModel.Ignore_GridFilter;
    }
    if (layoutModel.Ignore_ColumnFilters) {
        pivotLayout.ColumnFilters = layoutModel.Ignore_ColumnFilters;
    }
    if (layoutModel.Ignore_ColumnHeaders) {
        pivotLayout.ColumnHeaders = layoutModel.Ignore_ColumnHeaders;
    }
    if (layoutModel.Ignore_AutoSizeColumns != null) {
        pivotLayout.AutoSizeColumns = layoutModel.Ignore_AutoSizeColumns;
    }
    if (layoutModel.Ignore_IsReadOnly != null) {
        pivotLayout.IsReadOnly = layoutModel.Ignore_IsReadOnly;
    }
    if (layoutModel.Ignore_Tags) {
        pivotLayout.Tags = layoutModel.Ignore_Tags;
    }
    if (layoutModel.Ignore_Source) {
        pivotLayout.Source = layoutModel.Ignore_Source;
    }
    if (layoutModel.Ignore_AdaptableVersion) {
        pivotLayout.AdaptableVersion = layoutModel.Ignore_AdaptableVersion;
    }
    if (layoutModel.Ignore_Uuid) {
        pivotLayout.Uuid = layoutModel.Ignore_Uuid;
    }
    if (layoutModel.PivotGroupedColumns) {
        pivotLayout.PivotGroupedColumns = layoutModel.PivotGroupedColumns;
    }
    else {
        delete pivotLayout.PivotGroupedColumns;
    }
    if (layoutModel.RowGroupValues) {
        pivotLayout.RowGroupValues = (0, exports.toRowGroupValuesForLayoutState)(layoutModel.RowGroupValues);
    }
    else {
        delete pivotLayout.RowGroupValues;
    }
    if (layoutModel.GrandTotalRow != null) {
        pivotLayout.GrandTotalRow = layoutModel.GrandTotalRow;
    }
    else {
        delete pivotLayout.GrandTotalRow;
    }
    if (layoutModel.PivotGrandTotal != null) {
        pivotLayout.PivotGrandTotal = layoutModel.PivotGrandTotal;
    }
    else {
        delete pivotLayout.PivotGrandTotal;
    }
    if (layoutModel.PivotColumnTotal != null) {
        pivotLayout.PivotColumnTotal = layoutModel.PivotColumnTotal;
    }
    else {
        delete pivotLayout.PivotColumnTotal;
    }
    if (layoutModel.PivotAggregationColumns) {
        pivotLayout.PivotAggregationColumns = (layoutModel.PivotAggregationColumns || []).map(({ ColumnId, AggFunc, Total }) => ({
            ColumnId,
            AggFunc: toAggregationColumnValue(AggFunc),
            Total,
        }));
    }
    else {
        delete pivotLayout.PivotAggregationColumns;
    }
    if (layoutModel.ColumnGroupValues) {
        pivotLayout.ColumnGroupValues = {
            ColumnGroupDefaultBehavior: layoutModel.ColumnGroupValues.ColumnGroupDisplay,
        };
        if ((layoutModel.ColumnGroupValues.ColumnGroupDisplay === 'collapsed' ||
            layoutModel.ColumnGroupValues.ColumnGroupDisplay === 'expanded') &&
            layoutModel.ColumnGroupValues.Values) {
            // @ts-ignore
            pivotLayout.ColumnGroupValues.ExceptionGroupKeys = layoutModel.ColumnGroupValues.Values;
        }
    }
    return pivotLayout;
};
exports.pivotLayoutModelToPivotLayout = pivotLayoutModelToPivotLayout;
const isPivotLayout = (layout) => Array.isArray(layout.PivotColumns);
exports.isPivotLayout = isPivotLayout;
