import { useCallback, useContext, useState } from 'react';
import { startProcessInstance } from '@reltio/mdm-sdk';
import { WorkflowTasksContext } from '../../../contexts/WorkflowTasksContext';
import { showWorkflowError } from '../helpers/errors';
import { useMdmEntity, useMdmTenant, useMdmWorkflowEnvironmentUrl, useMdmWorkflowPath } from '../../../contexts/MdmModuleContext';
export var useWorkflowProcessInstance = function () {
    var _a = useState(false), loading = _a[0], setLoading = _a[1];
    var loadTasks = useContext(WorkflowTasksContext).loadTasks;
    var workflowPath = useMdmWorkflowPath();
    var environment = useMdmWorkflowEnvironmentUrl();
    var tenant = useMdmTenant();
    var entity = useMdmEntity();
    var entityUri = entity.uri;
    var processInstance = useCallback(function (comment, taskType) {
        setLoading(true);
        return startProcessInstance({
            workflowPath: workflowPath,
            tenant: tenant,
            environment: environment,
            processType: taskType,
            comment: comment,
            objectURIs: [entityUri]
        })
            .then(function () {
            loadTasks();
        })
            .catch(function (error) {
            showWorkflowError(error);
            throw error;
        })
            .finally(function () {
            setLoading(false);
        });
    }, [entityUri, environment, loadTasks, tenant, workflowPath]);
    return { processInstance: processInstance, loading: loading };
};
