import { useCallback } from 'react';
import { Directions, getDirectionalLabelFromObject } from '@reltio/mdm-sdk';
import { ascend, curry, evolve, pipe, prop, propEq, propOr, tap } from 'ramda';
export var useRelationTypeSelector = function (_a) {
    var reversedContextLabels = _a.reversedContextLabels;
    var getRelationTypesOptions = useCallback(function (inRelations, outRelations) {
        var labelsMap = {};
        var addLabelInMap = function (label) { return (labelsMap[label] = propOr(0, label, labelsMap) + 1); };
        var getDirectionalLabel = pipe(getDirectionalLabelFromObject, tap(addLabelInMap));
        var byLabel = ascend(prop('label'));
        var prepareRelation = curry(function (direction, _a) {
            var uri = _a.uri, label = _a.label, startObject = _a.startObject, endObject = _a.endObject;
            var dirObject = direction === (reversedContextLabels ? Directions.OUT : Directions.IN)
                ? startObject
                : endObject;
            return {
                label: { directionalLabel: getDirectionalLabel(dirObject), typeLabel: label },
                value: "".concat(uri, ",").concat(direction),
                startObject: startObject,
                endObject: endObject
            };
        });
        return inRelations
            .map(prepareRelation(Directions.IN))
            .concat(outRelations.map(prepareRelation(Directions.OUT)))
            .map(evolve({
            label: function (_a) {
                var directionalLabel = _a.directionalLabel, typeLabel = _a.typeLabel;
                return directionalLabel
                    ? labelsMap[directionalLabel] > 1
                        ? "".concat(directionalLabel, " (").concat(typeLabel, ")")
                        : directionalLabel
                    : typeLabel;
            }
        }))
            .sort(byLabel);
    }, [reversedContextLabels]);
    var fromEditorValue = useCallback(function (inRelationTypes, outRelationTypes) { return function (relation) {
        var _a = relation.value.split(','), uri = _a[0], direction = _a[1];
        var type = (direction === Directions.IN ? inRelationTypes : outRelationTypes).find(propEq('uri', uri));
        return { type: type, direction: direction };
    }; }, []);
    var toEditorValue = useCallback(function (relation, relationsTypesOptions) {
        return relationsTypesOptions.find(propEq('value', "".concat(relation.relationType, ",").concat(relation.direction)));
    }, []);
    return {
        getRelationTypesOptions: getRelationTypesOptions,
        fromEditorValue: fromEditorValue,
        toEditorValue: toEditorValue
    };
};
