import { useCallback } from 'react';
import { andThen, ifElse, isNil, pipe, identity } from 'ramda';
import { addCrosswalk, addCrosswalkInContributor, deleteCrosswalk, deleteCrosswalkAttribute, editCrosswalkAttribute } from '@reltio/mdm-sdk';
export var useCrosswalkActions = function (_a) {
    var _b = _a.onLoad, onLoad = _b === void 0 ? identity : _b, _c = _a.onSuccess, onSuccess = _c === void 0 ? identity : _c, _d = _a.onError, onError = _d === void 0 ? identity : _d;
    var handleRequest = useCallback(function (request) {
        onLoad();
        request
            .then(function (_a) {
            var errors = _a.errors;
            if (errors)
                throw errors;
            onSuccess();
        })
            .catch(onError);
    }, [onLoad, onError, onSuccess]);
    var addCrosswalkAction = useCallback(function (_a) {
        var entity = _a.entity, contributorCrosswalk = _a.contributorCrosswalk, crosswalk = _a.crosswalk;
        var addRequest = contributorCrosswalk
            ? addCrosswalkInContributor({
                entityTypeUri: entity.type,
                contributorCrosswalkType: contributorCrosswalk.type,
                contributorCrosswalkValue: contributorCrosswalk.value,
                contributorCrosswalkSourceTable: contributorCrosswalk.sourceTable,
                crosswalkType: crosswalk.type,
                crosswalkValue: crosswalk.value,
                crosswalkSourceTable: crosswalk.sourceTable,
                crosswalkDeleteDate: crosswalk.deleteDate
            })
            : addCrosswalk({ entityUri: entity.uri, crosswalk: crosswalk });
        pipe(andThen(function (_a) {
            var response = _a[0];
            return response;
        }), handleRequest)(addRequest);
    }, [handleRequest]);
    var editCrosswalkAction = useCallback(function (_a) {
        var entityUri = _a.entityUri, crosswalkId = _a.crosswalkId, attributeName = _a.attributeName, value = _a.value;
        pipe(ifElse(function (_a) {
            var value = _a.value;
            return isNil(value);
        }, deleteCrosswalkAttribute, editCrosswalkAttribute), andThen(function (_a) {
            var response = _a[0];
            return response;
        }), handleRequest)({
            entityUri: entityUri,
            crosswalkId: crosswalkId,
            attributeName: attributeName,
            value: value
        });
    }, [handleRequest]);
    var deleteCrosswalkAction = useCallback(function (_a) {
        var entityUri = _a.entityUri, crosswalkId = _a.crosswalkId;
        pipe(deleteCrosswalk, handleRequest)({
            entityUri: entityUri,
            crosswalkId: crosswalkId
        });
    }, [handleRequest]);
    return {
        addCrosswalk: addCrosswalkAction,
        editCrosswalk: editCrosswalkAction,
        deleteCrosswalk: deleteCrosswalkAction
    };
};
