var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
import { eqBy, path, reject } from 'ramda';
import { useEffect, useMemo, useRef } from 'react';
import { isEditableMode, getInvalidConnections, markEdited, markNew } from '@reltio/mdm-sdk';
import { useActionsHook } from '../../contexts/ActionsHookContext';
import { useMdmAction, useMdmAllRelationsToAddAndEdit, useMdmMode, useMdmProfileErrors, useMdmRelationsDrafts, useMdmListener } from '../../contexts/MdmModuleContext';
export var useExpandInvalidRelations = function (configId) {
    var openRelationEditor = useMdmAction('openRelationEditor');
    var mode = useMdmMode();
    var profileErrors = useMdmProfileErrors();
    var shouldOpenInvalidEditors = useRef(true);
    var listenToActions = useActionsHook();
    var _a = useMdmRelationsDrafts(configId) || {}, _b = _a.addedConnections, addedConnections = _b === void 0 ? [] : _b, _c = _a.editedConnections, editedConnections = _c === void 0 ? [] : _c;
    var relationsToAddAndEdit = useMdmAllRelationsToAddAndEdit([configId]) || [];
    var preparedConnectionsList = reject(function (draftConnection) {
        return relationsToAddAndEdit.some(eqBy(path(['relation', 'relationUri']), draftConnection));
    }, __spreadArray(__spreadArray([], addedConnections.map(markNew), true), editedConnections.map(markEdited), true));
    var invalidConnections = useMemo(function () { return getInvalidConnections(profileErrors, preparedConnectionsList); }, [profileErrors, preparedConnectionsList]);
    var expandInvalidRelatonsListener = useMdmListener('expandInvalidRelatonsListener');
    var setShouldOpenInvalidEditors = function (shouldOpen) { return (shouldOpenInvalidEditors.current = shouldOpen); };
    var listenerCallback = expandInvalidRelatonsListener(function () { return setShouldOpenInvalidEditors(true); });
    useEffect(function () {
        if (isEditableMode(mode) && invalidConnections.length && shouldOpenInvalidEditors.current) {
            invalidConnections.forEach(function (connection) { return openRelationEditor(configId, connection); });
            setShouldOpenInvalidEditors(false);
        }
    }, [mode, invalidConnections]);
    useEffect(function () {
        var stopListeningActions = listenToActions(listenerCallback);
        return function () { return stopListeningActions(); };
    }, [listenToActions]);
};
