package com.ffii.core.config.auth;

import java.io.IOException;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.LocaleResolver;

import com.ffii.core.user.entity.User;
import com.ffii.core.user.service.UserAttemptService;
import com.ffii.core.utils.LocaleUtils;

/** @author Fung */
@Component
public class SuccessHandler implements AuthenticationSuccessHandler {

	private LocaleResolver localeResolver;
	private UserAttemptService userAttemptService;

	public SuccessHandler(LocaleResolver localeResolver, UserAttemptService userAttemptService) {
		this.localeResolver = localeResolver;
		this.userAttemptService = userAttemptService;
	}

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		User user = (User) authentication.getPrincipal();
		if (StringUtils.isNotBlank(user.getLocale()))
			localeResolver.setLocale(request, response, LocaleUtils.from(user.getLocale()));
		userAttemptService.loginSuccess(authentication.getName());
	}

}
