package com.atlassian.stash.internal.rest.inject;

import com.atlassian.bitbucket.AuthorisationException;
import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.task.NoSuchTaskException;
import com.atlassian.bitbucket.task.Task;
import com.atlassian.bitbucket.task.TaskService;
import com.sun.jersey.api.core.HttpContext;

import javax.annotation.Nonnull;

import static com.atlassian.bitbucket.rest.util.ResourcePatterns.TASK_ID;
import static com.atlassian.stash.internal.rest.util.HttpContextUtils.requireSinglePathSegmentValue;

/**
 * Injects the context {@link Task} into a JAX-RS resource method that resides at a {@link javax.ws.rs.Path path}
 * beneath {@link com.atlassian.bitbucket.rest.util.ResourcePatterns#TASK_URI /tasks}.
 *
 * @since 3.3
 */
public class TaskInjectable extends AbstractResourceInjectable<Task> {

    private final I18nService i18nService;
    private final TaskService taskService;

    public TaskInjectable(I18nService i18nService, TaskService taskService) {
        this.i18nService = i18nService;
        this.taskService = taskService;
    }

    @Nonnull
    @Override
    public Task doGetValue(HttpContext httpContext) {
        String taskId = requireSinglePathSegmentValue(TASK_ID, httpContext, Task.class);
        return getTask(taskId);
    }

    private Task getTask(String taskId) {
        try {
            Task task = taskService.getById(Long.parseLong(taskId));
            if (task != null) {
                return task;
            }
        } catch (AuthorisationException | NumberFormatException e) {
            // no-op: the same error should be returned whether the task is missing or not visible to the user
        }

        throw new NoSuchTaskException(i18nService.createKeyedMessage("bitbucket.rest.task.nosuchtask", taskId));
    }

}
