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

import com.atlassian.stash.internal.web.soy.StashSoyResponseBuilder;
import com.atlassian.bitbucket.user.DetailedGroup;
import com.atlassian.bitbucket.user.DetailedUser;
import com.atlassian.bitbucket.user.UserAdminService;
import com.atlassian.bitbucket.util.Page;
import com.atlassian.bitbucket.util.PageUtils;
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.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/admin")
public final class UserAndGroupListController {

    private static final String USER_LIST = "bitbucket.internal.admin.users.list";
    private static final String GROUP_LIST = "bitbucket.internal.admin.groups.list";

    private final UserAdminService userAdminService;

    @Autowired
    public UserAndGroupListController(UserAdminService userAdminService) {
        this.userAdminService = userAdminService;
    }

    @RequestMapping(value = "/groups", method = RequestMethod.GET)
    public ModelAndView listGroups(@RequestParam(value = "filter", required = false, defaultValue = "") String filter) {
        Page<DetailedGroup> groups = userAdminService.findGroupsByName(filter, PageUtils.newRequest(0, 50));
        return new StashSoyResponseBuilder(GROUP_LIST)
                .put("filter", filter)
                .put("groupPage", groups)
                .build();
    }

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    public ModelAndView listUsers(@RequestParam(value = "filter", required = false, defaultValue = "") String filter) {
        Page<DetailedUser> users = userAdminService.findUsersByName(filter, PageUtils.newRequest(0, 50));
        return new StashSoyResponseBuilder(USER_LIST)
                .put("filter", filter)
                .put("userPage", users)
                .build();
    }
}
