import { useState, useCallback, useContext, useMemo } from 'react';
import i18n from 'ui-i18n';
import { updatePriorityForTask, WorkflowPriority } 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 useWorkflowPriority = function (_a) {
    var priority = _a.priority, 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 updatePriority = useCallback(function (newValue) {
        var newPriority = newValue.value;
        if (workflowPath && canUpdateTask && taskId && priority !== newPriority) {
            setUpdateRequestIsInProgress(true);
            safePromise(updatePriorityForTask({
                taskId: taskId,
                workflowPath: workflowPath,
                environment: environment,
                tenant: tenant,
                priority: newPriority
            }))
                .then(function () {
                updateTaskState === null || updateTaskState === void 0 ? void 0 : updateTaskState(taskId, { priority: newPriority });
            })
                .catch(showWorkflowError)
                .finally(function () {
                setUpdateRequestIsInProgress(false);
            });
        }
    }, [workflowPath, taskId, environment, tenant, updateTaskState, safePromise, priority, canUpdateTask]);
    var priorities = useMemo(function () { return [
        {
            label: i18n.text('Low'),
            value: WorkflowPriority.low
        },
        {
            label: i18n.text('Medium'),
            value: WorkflowPriority.medium
        },
        {
            label: i18n.text('High'),
            value: WorkflowPriority.high
        },
        {
            label: i18n.text('Urgent'),
            value: WorkflowPriority.urgent
        }
    ]; }, []);
    return { priorities: priorities, updatePriority: updatePriority, updateRequestIsInProgress: updateRequestIsInProgress, readOnly: !canUpdateTask };
};
