"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useWorkflowDueDate = void 0;
var react_1 = require("react");
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var useSafePromise_1 = require("../../../hooks/useSafePromise");
var WorkflowTasksContext_1 = require("../../../contexts/WorkflowTasksContext");
var MdmModuleContext_1 = require("../../../contexts/MdmModuleContext");
var errors_1 = require("../helpers/errors");
var common_1 = require("../helpers/common");
var useWorkflowCheckPermission_1 = require("./useWorkflowCheckPermission");
var useWorkflowDueDate = function (_a) {
    var dueDate = _a.dueDate, taskId = _a.taskId, isOpen = _a.isOpen;
    var updateTaskState = ((0, react_1.useContext)(WorkflowTasksContext_1.WorkflowTasksContext) || {}).updateTaskState;
    var workflowPath = (0, MdmModuleContext_1.useMdmWorkflowPath)();
    var environment = (0, MdmModuleContext_1.useMdmWorkflowEnvironmentUrl)();
    var tenant = (0, MdmModuleContext_1.useMdmTenant)();
    var safePromise = (0, useSafePromise_1.useSafePromise)();
    var _b = (0, react_1.useState)(false), updateRequestIsInProgress = _b[0], setUpdateRequestIsInProgress = _b[1];
    var checkWorkflowPermission = (0, useWorkflowCheckPermission_1.useWorkflowCheckPermission)();
    var canUpdateTask = checkWorkflowPermission('UPDATE_TASK') && (0, common_1.isOpenTask)(isOpen);
    var updateDueDate = (0, react_1.useCallback)(function (newValue) {
        if (workflowPath && canUpdateTask && taskId && newValue && dueDate !== newValue) {
            setUpdateRequestIsInProgress(true);
            safePromise((0, mdm_sdk_1.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(errors_1.showWorkflowError)
                .finally(function () {
                setUpdateRequestIsInProgress(false);
            });
        }
    }, [workflowPath, taskId, environment, tenant, updateTaskState, safePromise, dueDate, canUpdateTask]);
    return { updateDueDate: updateDueDate, updateRequestIsInProgress: updateRequestIsInProgress, readOnly: !canUpdateTask };
};
exports.useWorkflowDueDate = useWorkflowDueDate;
