import isEqual from 'lodash/isEqual';
import { isPivotLayoutModel } from '../../layout-manager/src/isPivotLayoutModel';
import { normalizeTableLayoutModel, normalizePivotLayoutModel, } from '../../layout-manager/src/normalizeLayoutModel';
import { simplifyTableLayoutModel, simplifyPivotLayoutModel, } from '../../layout-manager/src/simplifyLayoutModel';
import { isWeightedAverageAggregation, WEIGHTED_AVERAGE_AGG_FN_NAME, isWeightedAverageAggFuncName, } from '../../AdaptableState/Common/AggregationColumns';
import { removeAdaptableObjectPrimitivesInlineDeep } from '../../Utilities/Helpers/AdaptableHelper';
export function columnWidthsToColumnSizing(columnWidths) {
    if (!columnWidths) {
        return undefined;
    }
    return Object.keys(columnWidths).reduce((acc, colId) => {
        acc[colId] = { Width: columnWidths[colId] };
        return acc;
    }, {});
}
export const layoutStateToLayoutModel = (layout) => {
    if (isPivotLayout(layout)) {
        return pivotLayoutToPivotLayoutModel(layout);
    }
    return tableLayoutToTableLayoutModel(layout);
};
export const layoutModelToLayoutState = (layoutModel) => {
    if (isPivotLayoutModel(layoutModel)) {
        return pivotLayoutModelToPivotLayout(layoutModel);
    }
    return tableLayoutModelToTableLayout(layoutModel);
};
function cleanupAdaptableObjectPrimitives(layout) {
    const l = layout;
    for (const key in l) {
        if (key === 'ColumnFilters') {
            // we don't want to cleanup ColumnFilters
            // as we rely on the Uuids for identifying the filters
            if (Array.isArray(l[key])) {
                l[key].forEach((item) => {
                    if (typeof item === 'object') {
                        // but we do want to cleanup further down - eg: predicates in the filter
                        for (const k in item) {
                            if (typeof item[k] === 'object') {
                                removeAdaptableObjectPrimitivesInlineDeep(item[k]);
                            }
                        }
                    }
                });
            }
            continue;
        }
        if (typeof l[key] === 'object') {
            removeAdaptableObjectPrimitivesInlineDeep(l[key]);
        }
    }
}
/**
 * Compares 2 Layouts for equality
 * @param layout1 First Layout
 * @param layout2 Second Layout
 */
export const areLayoutsEqual = (layout1, layout2) => {
    if (!layout1 && !layout2) {
        return true;
    }
    if (!layout1 || !layout2) {
        return false;
    }
    return isEqual(normalizeLayout(layout1), normalizeLayout(layout2));
};
export const normalizeLayout = (layout, options) => {
    if (isPivotLayout(layout)) {
        return normalizePivotLayout(layout);
    }
    return normalizeTableLayout(layout, options);
};
export const normalizeTableLayout = (tableLayout, options) => {
    let model = tableLayoutToTableLayoutModel(tableLayout);
    model = normalizeTableLayoutModel(model, options);
    tableLayout = tableLayoutModelToTableLayout(model);
    return tableLayout;
};
export const normalizePivotLayout = (pivotLayout) => {
    let model = pivotLayoutToPivotLayoutModel(pivotLayout);
    model = normalizePivotLayoutModel(model);
    pivotLayout = pivotLayoutModelToPivotLayout(model);
    return pivotLayout;
};
const errorOnceMessages = new Map();
const errorOnce = (message) => {
    if (errorOnceMessages.get(message)) {
        return;
    }
    console.error(message);
    errorOnceMessages.set(message, true);
};
export 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 || [];
};
export 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;
};
export 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 || [],
    };
};
export 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;
            }, {});
        }
    }
};
export const tableLayoutToTableLayoutModel = (tableLayout) => {
    tableLayout = structuredClone(tableLayout);
    tableLayout.ColumnSizing =
        tableLayout.ColumnSizing ?? columnWidthsToColumnSizing(tableLayout.ColumnWidths);
    cleanupAdaptableObjectPrimitives(tableLayout);
    const TableAggregationColumns = (tableLayout.TableAggregationColumns || []).map(({ ColumnId, AggFunc }) => {
        return {
            ColumnId,
            AggFunc: toAggFunc(AggFunc),
        };
    });
    const result = simplifyTableLayoutModel({
        Name: tableLayout.Name,
        SuppressAggFuncInHeader: tableLayout.SuppressAggFuncInHeader,
        TableColumns: tableLayout.TableColumns,
        ColumnSizing: tableLayout.ColumnSizing,
        ColumnVisibility: tableLayout.ColumnVisibility,
        ColumnSorts: tableLayout.ColumnSorts,
        RowGroupedColumns: tableLayout.RowGroupedColumns,
        ColumnPinning: tableLayout.ColumnPinning,
        RowGroupValues: 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.Metadata) {
        result.Ignore_Metadata = tableLayout.Metadata;
    }
    if (tableLayout.RowSummaries != null) {
        result.Ignore_RowSummaries = tableLayout.RowSummaries;
    }
    return result;
};
export const pivotLayoutToPivotLayoutModel = (pivotLayout) => {
    pivotLayout = structuredClone(pivotLayout);
    pivotLayout.ColumnSizing =
        pivotLayout.ColumnSizing ?? columnWidthsToColumnSizing(pivotLayout.ColumnWidths);
    cleanupAdaptableObjectPrimitives(pivotLayout);
    const result = simplifyPivotLayoutModel({
        Name: pivotLayout.Name,
        SuppressAggFuncInHeader: pivotLayout.SuppressAggFuncInHeader,
        ColumnSizing: pivotLayout.ColumnSizing,
        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: 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.RowGroupDisplayType) {
        result.RowGroupDisplayType = pivotLayout.RowGroupDisplayType;
    }
    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;
    }
    if (pivotLayout.Metadata) {
        result.Ignore_Metadata = pivotLayout.Metadata;
    }
    return result;
};
function toAggFunc(aggFunc) {
    if (isWeightedAverageAggregation(aggFunc)) {
        return { aggFunc: WEIGHTED_AVERAGE_AGG_FN_NAME, weightedColumnId: aggFunc.weightedColumnId };
    }
    return { aggFunc };
}
export const tableLayoutModelToTableLayout = (layoutModel) => {
    const tableLayout = {
        Name: layoutModel.Name,
        TableColumns: layoutModel.TableColumns,
        ColumnSizing: layoutModel.ColumnSizing,
        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.Ignore_Metadata) {
        tableLayout.Metadata = layoutModel.Ignore_Metadata;
    }
    // if (layoutModel.RowGroupDisplayType) {
    tableLayout.RowGroupDisplayType = layoutModel.RowGroupDisplayType ?? 'single';
    // }
    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 = 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;
};
function toAggregationColumnValue(columnAggregationModel) {
    return columnAggregationModel &&
        typeof columnAggregationModel.aggFunc === 'string' &&
        isWeightedAverageAggFuncName(columnAggregationModel.aggFunc)
        ? {
            type: 'weightedAverage',
            weightedColumnId: columnAggregationModel.weightedColumnId,
        }
        : columnAggregationModel.aggFunc;
}
export const pivotLayoutModelToPivotLayout = (layoutModel) => {
    const pivotLayout = {
        Name: layoutModel.Name,
        PivotColumns: layoutModel.PivotColumns,
        TableColumns: layoutModel.TableColumns,
        ColumnSizing: layoutModel.ColumnSizing,
        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.Ignore_Metadata) {
        pivotLayout.Metadata = layoutModel.Ignore_Metadata;
    }
    if (layoutModel.PivotGroupedColumns) {
        pivotLayout.PivotGroupedColumns = layoutModel.PivotGroupedColumns;
    }
    else {
        delete pivotLayout.PivotGroupedColumns;
    }
    if (layoutModel.RowGroupValues) {
        pivotLayout.RowGroupValues = 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;
        }
    }
    // if (layoutModel.RowGroupDisplayType) {
    pivotLayout.RowGroupDisplayType = layoutModel.RowGroupDisplayType ?? 'single';
    // }
    return pivotLayout;
};
export const isPivotLayout = (layout) => Array.isArray(layout.PivotColumns);
