import isDeepEqual from 'lodash/isEqual';
import { debug as debugFactory } from '@infinite-table/infinite-react';
import { isPivotLayoutModel } from './isPivotLayoutModel';
import { normalizePivotLayoutModel, normalizeTableLayoutModel } from './normalizeLayoutModel';
const logger = debugFactory(`LayoutManager:Diffing`);
export const getChanges = (l1, l2) => {
    if (!l1 || typeof l1 !== 'object' || !l2 || typeof l2 !== 'object') {
        return [
            {
                key: 'missing',
                value1: l1,
                value2: l2,
            },
        ];
    }
    const k1 = Object.keys(l1);
    const k2 = Object.keys(l2);
    const allKeys = new Set([...k1, ...k2]);
    const changes = [];
    for (const key of allKeys) {
        if (!isDeepEqual(l1[key], l2[key])) {
            changes.push({ key, value1: l1[key], value2: l2[key] });
        }
    }
    return changes;
};
export const logChanges = (l1, l2, log) => {
    log = log || logger;
    const changes = getChanges(l1, l2);
    log('---');
    log('Layouts are not equal.');
    log('Layout 1', l1);
    log('Layout 2', l2);
    log('Differences:', changes);
    log('---');
};
export function isTableLayoutEqual(l1, l2) {
    l1 = normalizeTableLayoutModel(l1);
    l2 = normalizeTableLayoutModel(l2);
    clearIgnoredProperties(l1);
    clearIgnoredProperties(l2);
    const res = isDeepEqual(l1, l2);
    if (!res) {
        logChanges(l1, l2);
    }
    return res;
}
//#clearIgnoredProperties
function clearIgnoredProperties(layout) {
    delete layout.Ignore_GridFilter;
    delete layout.Ignore_ColumnFilters;
    delete layout.Ignore_ColumnHeaders;
    delete layout.Ignore_AutoSizeColumns;
    delete layout.Ignore_RowSummaries;
    delete layout.Ignore_IsReadOnly;
    delete layout.Ignore_Tags;
    delete layout.Ignore_Source;
    delete layout.Ignore_Metadata;
    delete layout.Ignore_AdaptableVersion;
    delete layout.Ignore_Uuid;
}
export function isPivotLayoutEqual(l1, l2) {
    l1 = normalizePivotLayoutModel(l1);
    l2 = normalizePivotLayoutModel(l2);
    clearIgnoredProperties(l1);
    clearIgnoredProperties(l2);
    const res = isDeepEqual(l1, l2);
    if (!res) {
        logChanges(l1, l2);
    }
    return res;
}
export function isLayoutEqual(l1, l2) {
    if (isPivotLayoutModel(l1) != isPivotLayoutModel(l2)) {
        return false;
    }
    if (isPivotLayoutModel(l1) && isPivotLayoutModel(l2)) {
        return isPivotLayoutEqual(l1, l2);
    }
    if (!isPivotLayoutModel(l1) && !isPivotLayoutModel(l2)) {
        return isTableLayoutEqual(l1, l2);
    }
    return false;
}
