package com.atlassian.stash.internal.web.users;

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.stash.internal.project.InternalProjectService;
import com.atlassian.stash.internal.web.soy.StashSoyResponseBuilder;
import com.atlassian.stash.internal.web.util.AvatarSupport;
import com.atlassian.bitbucket.project.PersonalProject;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.bitbucket.auth.AuthenticationContext;
import com.atlassian.bitbucket.user.UserService;
import com.atlassian.bitbucket.user.UserType;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @since 2.12
 */
public abstract class AbstractProfileController extends AvatarSupport {

    public static final String OTHERS_PROFILE_VIEW = "bitbucket.internal.users.profile.othersProfile";
    public static final String OWN_PROFILE_VIEW = "bitbucket.internal.users.profile.ownProfile";
    public static final String SERVICE_USER_PROFILE_VIEW = "bitbucket.internal.users.profile.serviceUserProfile";

    protected final AuthenticationContext authenticationContext;
    protected final UserService userService;

    private final InternalProjectService projectService;

    protected AbstractProfileController(I18nService i18nService, AuthenticationContext authenticationContext,
                                        InternalProjectService projectService, UserService userService) {
        super(i18nService);

        this.authenticationContext = authenticationContext;
        this.projectService = projectService;
        this.userService = userService;
    }

    protected void retrieveAvatar(@Nonnull ApplicationUser user, int size, @Nonnull HttpServletRequest request,
                                  @Nonnull HttpServletResponse response) throws IOException {
        streamAvatar(userService.getAvatar(user, size), request, response);
    }

    protected ModelAndView showProfile(@Nonnull ApplicationUser user) {
        if (user.getType() == UserType.SERVICE) {
            // service users don't have a personal project
            return new StashSoyResponseBuilder(SERVICE_USER_PROFILE_VIEW)
                    .put("user", user)
                    .build();
        }

        PersonalProject project = projectService.getPersonalProject(user);
        boolean isCurrentUser = user.equals(authenticationContext.getCurrentUser());

        StashSoyResponseBuilder builder = new StashSoyResponseBuilder(isCurrentUser ? OWN_PROFILE_VIEW : OTHERS_PROFILE_VIEW)
                .put("user", user)
                .putProject(project);

        return builder.build();
    }
}
