var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
import { useCallback } from 'react';
import { pipe } from 'ramda';
import { isAvailableRelationBetweenEntities, Directions, getRelationType, removeEntityAttribute, addEntityAttributes, changeEntityAttribute } from '@reltio/mdm-sdk';
import { useMdmMetadata } from '../../contexts/MdmModuleContext';
export var useEditableConnection = function (_a) {
    var connection = _a.connection, onConnectionChange = _a.onConnectionChange, relatedEntity = _a.relatedEntity;
    var metadata = useMdmMetadata();
    var onRelationChange = useCallback(function (relation) { return onConnectionChange(__assign(__assign({}, connection), { relation: relation })); }, [connection, onConnectionChange]);
    var handleAddAttributes = useCallback(pipe(addEntityAttributes(connection.relation), onRelationChange), [
        connection.relation,
        onRelationChange
    ]);
    var handleChangeAttribute = useCallback(pipe(changeEntityAttribute(connection.relation), onRelationChange), [
        connection.relation,
        onRelationChange
    ]);
    var handleRemoveAttribute = useCallback(pipe(removeEntityAttribute(connection.relation), onRelationChange), [
        connection.relation,
        onRelationChange
    ]);
    var handleChangeRelationType = useCallback(function (_a) {
        var type = _a.type, direction = _a.direction;
        var newConnection = {
            entity: connection.entity &&
                isAvailableRelationBetweenEntities(direction === Directions.OUT, connection.entity, relatedEntity, metadata, getRelationType(metadata, type))
                ? connection.entity
                : null,
            relation: __assign(__assign({}, connection.relation), { attributes: {}, type: type, direction: direction })
        };
        onConnectionChange(newConnection);
    }, [connection, onConnectionChange, relatedEntity, metadata]);
    var handleChangeEntity = useCallback(function (entity) { return onConnectionChange(__assign(__assign({}, connection), { entity: entity })); }, [connection, onConnectionChange]);
    return {
        onAddAttributes: handleAddAttributes,
        onChangeAttribute: handleChangeAttribute,
        onRemoveAttribute: handleRemoveAttribute,
        onChangeEntity: handleChangeEntity,
        onChangeRelationType: handleChangeRelationType
    };
};
