package eu.dnetlib.functionality.modular.ui;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import eu.dnetlib.functionality.modular.ui.users.AuthorizationDAO;
import eu.dnetlib.functionality.modular.ui.users.PermissionLevel;
import eu.dnetlib.functionality.modular.ui.users.User;

@Controller
public class UsersInternalController {
	
	@Resource(name="modularUiAuthorizationDao")
	private AuthorizationDAO dao;
	
	private static final Log log = LogFactory.getLog(UsersInternalController.class);
	
	@RequestMapping(value = "/ui/users.get")
	public @ResponseBody List<User> listUsers(HttpServletResponse response) throws IOException {
		final List<User> list = Lists.newArrayList();
		for (Map.Entry<String, Set<PermissionLevel>> e : dao.getPermissionLevels().entrySet()) {
			final User user = new User(e.getKey());
			user.setPermissionLevels(e.getValue());
			list.add(user);
		}
		Collections.sort(list);
		
		return list;
	}

	@RequestMapping(value = "/ui/saveusers.do", method=RequestMethod.POST)
	public @ResponseBody boolean updateUsers(@RequestBody final List<User> users) {
		
		log.info("Saving " + users.size() + " user(s)");
		final Map<String, Set<PermissionLevel>> map = Maps.newHashMap();
		for (User u : users) {
			map.put(u.getId(), u.getPermissionLevels());
		}
		dao.updatePermissionLevels(map);
		return true;
	}

}
