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

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.pull.NoSuchPullRequestException;
import com.atlassian.bitbucket.pull.PullRequest;
import com.atlassian.bitbucket.pull.PullRequestService;
import com.atlassian.bitbucket.repository.Repository;
import com.sun.jersey.api.core.HttpContext;

import javax.annotation.Nonnull;
import javax.ws.rs.Path;

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

/**
 * Injects the context {@link PullRequest} into a JAX-RS resource method that resides at a {@link Path path} beneath
 * {@link com.atlassian.bitbucket.rest.util.ResourcePatterns#PULL_REQUEST_URI}.
 *
 * @since 2.0
 */
public class PullRequestInjectable extends AbstractResourceInjectable<PullRequest> {

    private final I18nService i18nService;
    private final PullRequestService pullRequestService;
    private final RepositoryInjectable repositoryInjectable;

    public PullRequestInjectable(I18nService i18nService, PullRequestService pullRequestService,
                                 RepositoryInjectable repositoryInjectable) {
        this.i18nService = i18nService;
        this.pullRequestService = pullRequestService;
        this.repositoryInjectable = repositoryInjectable;
    }

    @Nonnull
    @Override
    public PullRequest doGetValue(HttpContext httpContext) {
        Repository repository = repositoryInjectable.getValue(httpContext);
        String pullRequestId = requireSinglePathSegmentValue(PULL_REQUEST_ID, httpContext, PullRequest.class);

        PullRequest pullRequest = pullRequestService.getById(repository.getId(), Long.parseLong(pullRequestId));
        if (pullRequest == null) {
            throw new NoSuchPullRequestException(i18nService.createKeyedMessage("bitbucket.rest.nosuchpullrequest",
                    pullRequestId, repository.getProject().getKey(), repository.getSlug()));
        }
        return pullRequest;
    }
}
