import { useState, useEffect, useCallback, useContext } from 'react';
import { addCommentForTask, getTaskById } from '@reltio/mdm-sdk';
import { useSafePromise } from '../../../hooks/useSafePromise';
import { WorkflowTasksContext } from '../../../contexts/WorkflowTasksContext';
import { showWorkflowError } from '../helpers/errors';
import { isOpenTask } from '../helpers/common';
import { useWorkflowCheckPermission } from './useWorkflowCheckPermission';
import { useMdmTenant, useMdmWorkflowEnvironmentUrl, useMdmWorkflowPath } from '../../../contexts/MdmModuleContext';
export var useWorkflowComments = function (_a) {
    var processInstanceComments = _a.processInstanceComments, taskId = _a.taskId, isOpen = _a.isOpen, onCommentWrite = _a.onCommentWrite;
    var updateTaskState = (useContext(WorkflowTasksContext) || {}).updateTaskState;
    var workflowPath = useMdmWorkflowPath();
    var environment = useMdmWorkflowEnvironmentUrl();
    var tenant = useMdmTenant();
    var safePromise = useSafePromise();
    var _b = useState([]), comments = _b[0], setComments = _b[1];
    var _c = useState(false), requestIsInProgress = _c[0], setRequestIsInProgress = _c[1];
    var checkWorkflowPermission = useWorkflowCheckPermission();
    var canUpdateTask = checkWorkflowPermission('UPDATE_TASK') && isOpenTask(isOpen);
    useEffect(function () {
        setComments(processInstanceComments || []);
    }, [processInstanceComments]);
    var writeComment = useCallback(function (comment) {
        if (canUpdateTask) {
            setRequestIsInProgress(true);
            safePromise(addCommentForTask({
                workflowPath: workflowPath,
                environment: environment,
                tenant: tenant,
                taskId: taskId,
                comment: comment
            }).then(function () {
                return getTaskById({
                    workflowPath: workflowPath,
                    environment: environment,
                    tenant: tenant,
                    taskId: taskId
                });
            }))
                .then(function (_a) {
                var processInstanceComments = _a.processInstanceComments;
                setComments(processInstanceComments || []);
                updateTaskState === null || updateTaskState === void 0 ? void 0 : updateTaskState(taskId, { processInstanceComments: processInstanceComments });
                onCommentWrite === null || onCommentWrite === void 0 ? void 0 : onCommentWrite({ processInstanceComments: processInstanceComments });
            })
                .catch(showWorkflowError)
                .finally(function () { return setRequestIsInProgress(false); });
        }
    }, [environment, taskId, tenant, workflowPath, safePromise, updateTaskState, canUpdateTask, onCommentWrite]);
    return { comments: comments, requestIsInProgress: requestIsInProgress, writeComment: writeComment, readOnly: !canUpdateTask };
};
