"use strict";
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);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useEditableConnection = void 0;
var react_1 = require("react");
var ramda_1 = require("ramda");
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var MdmModuleContext_1 = require("../../contexts/MdmModuleContext");
var useEditableConnection = function (_a) {
    var connection = _a.connection, onConnectionChange = _a.onConnectionChange, relatedEntity = _a.relatedEntity;
    var metadata = (0, MdmModuleContext_1.useMdmMetadata)();
    var onRelationChange = (0, react_1.useCallback)(function (relation) { return onConnectionChange(__assign(__assign({}, connection), { relation: relation })); }, [connection, onConnectionChange]);
    var handleAddAttributes = (0, react_1.useCallback)((0, ramda_1.pipe)((0, mdm_sdk_1.addEntityAttributes)(connection.relation), onRelationChange), [
        connection.relation,
        onRelationChange
    ]);
    var handleChangeAttribute = (0, react_1.useCallback)((0, ramda_1.pipe)((0, mdm_sdk_1.changeEntityAttribute)(connection.relation), onRelationChange), [
        connection.relation,
        onRelationChange
    ]);
    var handleRemoveAttribute = (0, react_1.useCallback)((0, ramda_1.pipe)((0, mdm_sdk_1.removeEntityAttribute)(connection.relation), onRelationChange), [
        connection.relation,
        onRelationChange
    ]);
    var handleChangeRelationType = (0, react_1.useCallback)(function (_a) {
        var type = _a.type, direction = _a.direction;
        var newConnection = {
            entity: connection.entity &&
                (0, mdm_sdk_1.isAvailableRelationBetweenEntities)(direction === mdm_sdk_1.Directions.OUT, connection.entity, relatedEntity, metadata, (0, mdm_sdk_1.getRelationType)(metadata, type))
                ? connection.entity
                : null,
            relation: __assign(__assign({}, connection.relation), { attributes: {}, type: type, direction: direction })
        };
        onConnectionChange(newConnection);
    }, [connection, onConnectionChange, relatedEntity, metadata]);
    var handleChangeEntity = (0, react_1.useCallback)(function (entity) { return onConnectionChange(__assign(__assign({}, connection), { entity: entity })); }, [connection, onConnectionChange]);
    return {
        onAddAttributes: handleAddAttributes,
        onChangeAttribute: handleChangeAttribute,
        onRemoveAttribute: handleRemoveAttribute,
        onChangeEntity: handleChangeEntity,
        onChangeRelationType: handleChangeRelationType
    };
};
exports.useEditableConnection = useEditableConnection;
