import { useState, useCallback, useContext } from 'react';
import { updateDueDateForTask } from '@reltio/mdm-sdk';
import { useSafePromise } from '../../../hooks/useSafePromise';
import { WorkflowTasksContext } from '../../../contexts/WorkflowTasksContext';
import { useMdmTenant, useMdmWorkflowEnvironmentUrl, useMdmWorkflowPath } from '../../../contexts/MdmModuleContext';
import { showWorkflowError } from '../helpers/errors';
import { isOpenTask } from '../helpers/common';
import { useWorkflowCheckPermission } from './useWorkflowCheckPermission';
export var useWorkflowDueDate = function (_a) {
    var dueDate = _a.dueDate, taskId = _a.taskId, isOpen = _a.isOpen;
    var updateTaskState = (useContext(WorkflowTasksContext) || {}).updateTaskState;
    var workflowPath = useMdmWorkflowPath();
    var environment = useMdmWorkflowEnvironmentUrl();
    var tenant = useMdmTenant();
    var safePromise = useSafePromise();
    var _b = useState(false), updateRequestIsInProgress = _b[0], setUpdateRequestIsInProgress = _b[1];
    var checkWorkflowPermission = useWorkflowCheckPermission();
    var canUpdateTask = checkWorkflowPermission('UPDATE_TASK') && isOpenTask(isOpen);
    var updateDueDate = useCallback(function (newValue) {
        if (workflowPath && canUpdateTask && taskId && newValue && dueDate !== newValue) {
            setUpdateRequestIsInProgress(true);
            safePromise(updateDueDateForTask({
                taskId: taskId,
                workflowPath: workflowPath,
                environment: environment,
                tenant: tenant,
                dueDate: newValue
            }))
                .then(function () {
                updateTaskState === null || updateTaskState === void 0 ? void 0 : updateTaskState(taskId, { dueDate: newValue });
            })
                .catch(showWorkflowError)
                .finally(function () {
                setUpdateRequestIsInProgress(false);
            });
        }
    }, [workflowPath, taskId, environment, tenant, updateTaskState, safePromise, dueDate, canUpdateTask]);
    return { updateDueDate: updateDueDate, updateRequestIsInProgress: updateRequestIsInProgress, readOnly: !canUpdateTask };
};
