package it.mice.voila.runtime.security.jaas;

import it.mice.voila.runtime.security.UserDetailImpl;
import it.mice.voila.runtime.security.UserProfileGrantedAuthorityImpl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;

public class JaasAuthenticationProviderAdapter implements AuthenticationProvider {
	private AuthenticationProvider jaasAuthenticationProvider;

	/**
	 * @return the jaasAuthenticationProvider
	 */
	public AuthenticationProvider getJaasAuthenticationProvider() {
		return jaasAuthenticationProvider;
	}

	/**
	 * @param jaasAuthenticationProvider the jaasAuthenticationProvider to set
	 */
	public void setJaasAuthenticationProvider(
			AuthenticationProvider jaasAuthenticationProvider) {
		this.jaasAuthenticationProvider = jaasAuthenticationProvider;
	}

	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		
		Authentication result = getJaasAuthenticationProvider().authenticate(authentication);
		
		if (result != null) {
			Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
			Iterator<? extends GrantedAuthority> i = result.getAuthorities().iterator();
			while (i.hasNext()) {
				GrantedAuthority grantedAuthority = (GrantedAuthority) i.next();
				UserProfileGrantedAuthorityImpl authImpl = new UserProfileGrantedAuthorityImpl(null, grantedAuthority.getAuthority(), null, null, null, null, null);
				auths.add(authImpl);
			}
			UserDetailImpl userDetail = new UserDetailImpl(result.getPrincipal().toString(), result.getCredentials().toString(), true, true, true, true, auths, null);
			UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetail, result.getCredentials(), auths);
			return auth;
		}
		
		return result;
	}

	public boolean supports(Class<? extends Object> authentication) {
		return getJaasAuthenticationProvider().supports(authentication);
	}

}
