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 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 (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 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);
    cleanupAdaptableObjectPrimitives(tableLayout);
    const TableAggregationColumns = (tableLayout.TableAggregationColumns || []).map(({ ColumnId, AggFunc }) => {
        return {
            ColumnId,
            AggFunc: toAggFunc(AggFunc),
        };
    });
    const result = 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: tableLayout.RowGroupValues
            ? tableLayout.RowGroupValues.RowGroupDefaultBehavior === 'always-collapsed' ||
                tableLayout.RowGroupValues.RowGroupDefaultBehavior === 'always-expanded'
                ? {
                    RowGroupDisplay: tableLayout.RowGroupValues.RowGroupDefaultBehavior,
                }
                : {
                    RowGroupDisplay: tableLayout.RowGroupValues.RowGroupDefaultBehavior,
                    Values: tableLayout.RowGroupValues.ExceptionGroupKeys || [],
                }
            : undefined,
        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;
};
export const pivotLayoutToPivotLayoutModel = (pivotLayout) => {
    pivotLayout = structuredClone(pivotLayout);
    cleanupAdaptableObjectPrimitives(pivotLayout);
    const result = 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: pivotLayout.RowGroupValues
            ? pivotLayout.RowGroupValues.RowGroupDefaultBehavior === 'always-collapsed' ||
                pivotLayout.RowGroupValues.RowGroupDefaultBehavior === 'always-expanded'
                ? {
                    RowGroupDisplay: pivotLayout.RowGroupValues.RowGroupDefaultBehavior,
                }
                : {
                    RowGroupDisplay: pivotLayout.RowGroupValues.RowGroupDefaultBehavior,
                    Values: pivotLayout.RowGroupValues.ExceptionGroupKeys || [],
                }
            : undefined,
        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;
};
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.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 = {
            RowGroupDefaultBehavior: layoutModel.RowGroupValues.RowGroupDisplay,
        };
        if ((layoutModel.RowGroupValues.RowGroupDisplay === 'collapsed' ||
            layoutModel.RowGroupValues.RowGroupDisplay === 'expanded') &&
            layoutModel.RowGroupValues.Values) {
            // @ts-ignore
            tableLayout.RowGroupValues.ExceptionGroupKeys = layoutModel.RowGroupValues.Values;
        }
    }
    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.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 = {
            RowGroupDefaultBehavior: layoutModel.RowGroupValues.RowGroupDisplay,
        };
        if ((layoutModel.RowGroupValues.RowGroupDisplay === 'collapsed' ||
            layoutModel.RowGroupValues.RowGroupDisplay === 'expanded') &&
            layoutModel.RowGroupValues.Values) {
            // @ts-ignore
            pivotLayout.RowGroupValues.ExceptionGroupKeys = layoutModel.RowGroupValues.Values;
        }
    }
    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;
};
export const isPivotLayout = (layout) => Array.isArray(layout.PivotColumns);
