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

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.stash.internal.web.soy.StashSoyResponseBuilder;
import com.atlassian.bitbucket.project.Project;
import com.atlassian.bitbucket.project.ProjectService;
import com.atlassian.bitbucket.project.ProjectType;
import com.atlassian.bitbucket.permission.Permission;
import com.atlassian.bitbucket.permission.PermissionAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

@Controller
@RequestMapping("/projects/{projectKey}/permissions")
public class ProjectPermissionsController extends BasePermissionController {

    public static final String PROJECT_EDIT_PERMISSIONS = "bitbucket.internal.project.projectPermissions";

    private final ProjectService projectService;

    @Autowired
    public ProjectPermissionsController(PermissionAdminService permissionAdminService,
                                        I18nService i18nService,
                                        ProjectService projectService) {
        super(permissionAdminService, i18nService);
        this.projectService = projectService;
    }

    @RequestMapping(method = GET)
    public ModelAndView editProjectPermissions(@PathVariable("projectKey") String projectKey) {
        Project project = projectService.getByKey(projectKey);
        if (project == null) {
            throw newNoSuchProjectException(projectKey);
        }
        if (project.getType() == ProjectType.PERSONAL) {
            throw new AccessDeniedException(i18nService.getMessage("bitbucket.web.project.personal.permissions.not.modifiable"));
        }
        return new StashSoyResponseBuilder(PROJECT_EDIT_PERMISSIONS)
                .put("project", project)
                .put("allRead", permissionAdminService.hasAllProjectPermission(Permission.PROJECT_READ, project) || permissionAdminService.hasAllProjectPermission(Permission.PROJECT_WRITE, project)) //write => read
                .put("allWrite", permissionAdminService.hasAllProjectPermission(Permission.PROJECT_WRITE, project))
                .put("permissionDataList", getPermissionData(Permission.PROJECT_ADMIN, Permission.PROJECT_WRITE, Permission.PROJECT_READ))
                .build();
    }
}
