package info.bukova.isspst.security;

import info.bukova.isspst.Constants;
import info.bukova.isspst.data.User;
import info.bukova.isspst.services.users.LdapUserImporter;
import info.bukova.isspst.services.users.RoleService;
import info.bukova.isspst.services.users.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator;

import java.util.Collection;

public class AuthPopulator implements LdapAuthoritiesPopulator {

	private UserService userService;
	private RoleService roleService;

	public AuthPopulator(UserService userService, RoleService roleService) {
		this.userService = userService;
		this.roleService = roleService;
		userService.setAuthMethod(AuthMethod.LDAP);
	}

	@Override
	public Collection<? extends GrantedAuthority> getGrantedAuthorities(
			DirContextOperations userData, String login) {

		User user;

		try {
			user = (User) userService.loadUserByUsername(login);
		} catch (UsernameNotFoundException e) {
			Logger logger = LoggerFactory.getLogger(AuthPopulator.class);
			logger.info("Importing user from LDAP");
			
			LdapUserImporter importer = new LdapUserImporter(userService);
			importer.importUser(login, userData, roleService.getRoleByAuthority(Constants.ROLE_USER));
			
			user = (User) userService.loadUserByUsername(login);
		}

		return user != null ? user.getAuthorities() : null;
	}

}
