"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useWorkflowDefinitions = void 0;
var react_1 = require("react");
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var useSafePromise_1 = require("../../../hooks/useSafePromise");
var MdmModuleContext_1 = require("../../../contexts/MdmModuleContext");
var filterDefinitions = function (definitions, entityTypeUri) {
    return definitions.filter(function (_a) {
        var manualStart = _a.manualStart, objectTypes = _a.objectTypes;
        return manualStart && (!objectTypes || (objectTypes === null || objectTypes === void 0 ? void 0 : objectTypes.some(function (uri) { return uri === entityTypeUri; })));
    });
};
var memoizedProcessDefinitions = (0, mdm_sdk_1.memoizeWith)(function (_a) {
    var workflowPath = _a.workflowPath, environment = _a.environment, tenant = _a.tenant;
    return "".concat(workflowPath, "-").concat(environment, "-").concat(tenant);
}, mdm_sdk_1.processDefinitions);
var useWorkflowDefinitions = function (_a) {
    var _b = _a === void 0 ? {} : _a, _c = _b.all, all = _c === void 0 ? false : _c, _d = _b.canViewDefinitions, canViewDefinitions = _d === void 0 ? true : _d;
    var _e = (0, react_1.useState)([]), definitions = _e[0], setDefinitions = _e[1];
    var _f = (0, react_1.useState)(false), loading = _f[0], setLoading = _f[1];
    var workflowPath = (0, MdmModuleContext_1.useMdmWorkflowPath)();
    var environment = (0, MdmModuleContext_1.useMdmWorkflowEnvironmentUrl)();
    var tenant = (0, MdmModuleContext_1.useMdmTenant)();
    var entity = (0, MdmModuleContext_1.useMdmEntity)();
    var entityType = entity === null || entity === void 0 ? void 0 : entity.type;
    var safePromise = (0, useSafePromise_1.useSafePromise)();
    (0, react_1.useEffect)(function () {
        if (!canViewDefinitions) {
            return;
        }
        setLoading(true);
        safePromise(memoizedProcessDefinitions({ workflowPath: workflowPath, environment: environment, tenant: tenant }))
            .then(function (_a) {
            var data = _a.data;
            if (!data) {
                return;
            }
            setDefinitions(all ? data : filterDefinitions(data, entityType));
        })
            .catch(function (error) {
            console.warn('Workflow error', error);
        })
            .finally(function () {
            setLoading(false);
        });
    }, [entityType, workflowPath, environment, tenant, all, canViewDefinitions]);
    return (0, react_1.useMemo)(function () { return ({ definitions: definitions, loading: loading }); }, [definitions, loading]);
};
exports.useWorkflowDefinitions = useWorkflowDefinitions;
