package eu.dnetlib.functionality.modular.ui.users;

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Required;

import com.google.common.collect.Sets;

public class SimpleAuthorizationManager implements AuthorizationManager {
	
	
	private AuthorizationDAO authorizationDAO;
	
	private String defaultSuperAdmin;
	
	@Override
	public User obtainUserDetails(final HttpServletRequest request) {
		final Principal principal = request.getUserPrincipal();
		
		final User user = new User();
		
		if (principal != null) {
	        final String username = principal.getName();
	        if (username != null) {
	        	user.setId(username);
	        	user.setFullname(username);
	        	user.setPermissionLevels(authorizationDAO.getPermissionLevels(username));
	        	if (username.equals(getDefaultSuperAdmin())) {
	        		user.getPermissionLevels().add(PermissionLevel.SUPER_ADMIN);
	        	}
	        } else {
	        	user.setId("anonymous");
	        	user.setFullname("anonymous");
	        	user.setPermissionLevels(Sets.newHashSet(PermissionLevel.GUEST));
	        }
	    }
		
		return user;
	}

	public AuthorizationDAO getAuthorizationDAO() {
		return authorizationDAO;
	}

	@Required
	public void setAuthorizationDAO(AuthorizationDAO authorizationDAO) {
		this.authorizationDAO = authorizationDAO;
	}

	public String getDefaultSuperAdmin() {
		return defaultSuperAdmin;
	}

	@Required
	public void setDefaultSuperAdmin(String defaultSuperAdmin) {
		this.defaultSuperAdmin = defaultSuperAdmin;
	}

}
