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

import com.atlassian.bitbucket.auth.AuthenticationContext;
import com.atlassian.bitbucket.nav.NavBuilder;
import com.atlassian.bitbucket.project.ProjectService;
import com.atlassian.bitbucket.server.FeatureManager;
import com.atlassian.bitbucket.server.StandardFeature;
import com.atlassian.bitbucket.util.PageUtils;
import com.atlassian.stash.internal.web.soy.StashSoyResponseBuilder;
import com.google.common.collect.ImmutableMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/dashboard")
public class DashboardController {

    private static final String VIEW = "bitbucket.internal.page.dashboard";

    private final AuthenticationContext authenticationContext;
    private final FeatureManager featureManager;
    private final NavBuilder navBuilder;
    private final ProjectService projectService;

    @Autowired
    public DashboardController(AuthenticationContext authenticationContext,
                               FeatureManager featureManager,
                               NavBuilder navBuilder,
                               ProjectService projectService) {
        this.authenticationContext = authenticationContext;
        this.featureManager = featureManager;
        this.navBuilder = navBuilder;
        this.projectService = projectService;
    }

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView dashboard() {
        if (authenticationContext.isAuthenticated()) {
            return renderDashboard();
        }

        // If user is not logged in, redirect to the projects list only if public projects are available
        // TODO: See if there's a better approach to get the user back to the dashboard in this scenario if they login
        if (featureManager.isEnabled(StandardFeature.PUBLIC_ACCESS) &&
                projectService.findAll(PageUtils.newRequest(0, 1)).getSize() != 0) {
            return new ModelAndView("redirect:" + navBuilder.allProjects().buildRelNoContext());
        }

        return new ModelAndView("redirect:" + navBuilder.login().buildRelNoContext(),
                ImmutableMap.of("nextUrl", navBuilder.dashboard().buildRelNoContext()));

    }

    private ModelAndView renderDashboard() {
        return new StashSoyResponseBuilder(VIEW)
                .put("currentUser", authenticationContext.getCurrentUser())
                .build();
    }

}
