import { useEffect } from 'react';
import { evolve, map } from 'ramda';
import { entity as History, HistoryMode, wrapInArrayIfNeeded } from '@reltio/mdm-sdk';
import { useMdmAction, useMdmEntity, useMdmHistoryDiff, useMdmHistoryMode, useMdmHistorySlice } from '../../../contexts/MdmModuleContext';
import { DEFAULT_HISTORY_DIFF } from '../constants';
var fixRefEntity = evolve({
    refEntity: wrapInArrayIfNeeded,
    refRelation: wrapInArrayIfNeeded
});
var prepareHistorySlice = function (entity) {
    if (entity) {
        return evolve({
            attributes: map(map(fixRefEntity))
        })(entity);
    }
    return entity;
};
export var useHistoryDiff = function () {
    var setHistoryDiff = useMdmAction('setHistoryDiff');
    var clearHistoryDiff = useMdmAction('clearHistoryDiff');
    var historySlice = useMdmHistorySlice();
    var historyDiff = useMdmHistoryDiff();
    var historyMode = useMdmHistoryMode();
    var entity = useMdmEntity();
    useEffect(function () {
        if (historySlice) {
            var aEntity = historySlice.aEntity, bEntity = historySlice.bEntity;
            var historyManager = History.HistoryManager.createHistoryManager();
            var historyDiff_1 = historyManager.computeEntityHistoryDiff(prepareHistorySlice(historyMode === HistoryMode.Current ? entity : bEntity), prepareHistorySlice(aEntity));
            setHistoryDiff(historyDiff_1);
        }
        else {
            clearHistoryDiff();
        }
    }, [historySlice, historyMode, setHistoryDiff, entity]);
    return historyDiff || DEFAULT_HISTORY_DIFF;
};
