/**
 * 
 */
package de.bstly.board.security;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;

import de.bstly.board.businesslogic.UserManager;
import de.bstly.board.model.LocalUser;

/**
 * The Class OAuth2AuthenticationSuccessHandler.
 */
@Component
public class OAuth2AuthenticationSuccessHandler
		extends SavedRequestAwareAuthenticationSuccessHandler {

	@Autowired
	private UserManager localUserManager;

	private RememberMeServices rememberMeServices;


	/*
	 * @see org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication)
	 */
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		LocalUser localUser = localUserManager.getByAuth(authentication);

		UserDetails userDetails = localUserManager.loadUserByUsername(localUser.getUsername());

		List<GrantedAuthority> authorities = Lists.newArrayList();
		authorities.addAll(authentication.getAuthorities());
		authorities.addAll(userDetails.getAuthorities());

		UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(
				userDetails, null, authorities);

		SecurityContextHolder.getContext().setAuthentication(newAuthentication);

		if (rememberMeServices != null) {
			request.setAttribute("remember-me", "true");
			rememberMeServices.loginSuccess(request, response, newAuthentication);
		}

		handle(request, response, newAuthentication);
		clearAuthenticationAttributes(request);
	}

	/**
	 * Sets the remember me services.
	 *
	 * @param rememberMeServices the new remember me services
	 */
	public void setRememberMeServices(RememberMeServices rememberMeServices) {
		this.rememberMeServices = rememberMeServices;
	}

}
