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

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.bitbucket.user.NoSuchUserException;
import com.atlassian.bitbucket.user.UserService;
import com.sun.jersey.api.core.HttpContext;

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

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

/**
 * Injects the context {@link ApplicationUser} into a JAX-RS resource method that resides at a {@link Path path} beneath
 * {@link com.atlassian.bitbucket.rest.util.ResourcePatterns#USER_URI /users/&lt;userId&gt;}.
 *
 * @since 2.0
 */
public class UserInjectable extends AbstractResourceInjectable<ApplicationUser> {

    private final I18nService i18nService;
    private final UserService userService;

    public UserInjectable(I18nService i18nService, UserService userService) {
        this.i18nService = i18nService;
        this.userService = userService;
    }

    @Nonnull
    @Override
    public ApplicationUser doGetValue(HttpContext httpContext) {
        String userSlug = requireSinglePathSegmentValue(USER_SLUG, httpContext, ApplicationUser.class);

        ApplicationUser user = userSlug == null ? null : userService.getUserBySlug(userSlug);
        if (user == null) {
            throw new NoSuchUserException(i18nService.createKeyedMessage("bitbucket.rest.nosuchuser", userSlug), userSlug);
        }
        return user;
    }
}
