package de.champonthis.buntspecht.security.handler;

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

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 de.champonthis.buntspecht.businesslogic.UserManager;
import de.champonthis.buntspecht.model.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


@Component
public class OAuth2AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

	@Autowired
	private UserManager userManager;

	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 {
		User user = userManager.getByAuth(authentication);

		UserDetails userDetails = userManager.loadUserByUsername(user.getUsername());

		List<GrantedAuthority> authorities = new ArrayList<>();
		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);
	}

	
	public void setRememberMeServices(RememberMeServices rememberMeServices) {
		this.rememberMeServices = rememberMeServices;
	}

}
