package com.style24.scm.support.security.handler;

import java.io.IOException;

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.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.style24.scm.biz.service.TssLoginService;
import com.style24.scm.support.security.TssLoginDetails;
import com.style24.scm.support.security.session.TssSession;

import lombok.extern.slf4j.Slf4j;

/**
 * 로그인 성공 시 호출되는 Handler
 * 
 * @author gagamel
 * @since 2020. 10. 19
 */
@Component
@Slf4j
public class TssLoginSuccessHandler implements AuthenticationSuccessHandler {

	@Autowired
	private TssLoginService loginService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		// 로그인 상세 정보
		TssLoginDetails loginDetails = (TssLoginDetails)authentication.getDetails();

		Integer userNo = loginDetails.getLoginInfo().getUserNo();
		log.info("userNo: {}", userNo);

		// 로그인 성공 시 로그인실패수가 0보다 크면 로그인실패수 reset
		int failCnt = loginService.getLoginFailCount(userNo);
		if (failCnt > 0) {
			loginService.createLoginFail(userNo, "N");
		}

		// 로그인 메뉴 목록
		loginDetails.setLoginMenuList(loginService.getLoginMenuList(userNo));

		// 최종로그인일시 Update
		loginService.updateLastLoginDate(userNo);

		// 로그인이력 남기기
		loginService.createLoginHistory(userNo);

		// 세션 생성
		this.createSession(request, loginDetails);

		response.sendRedirect("/");
	}

	/**
	 * Session 생성
	 * 
	 * @param request - HttpServletRequest
	 * @param loginDetails - 로그인 상세 정보
	 */
	private void createSession(HttpServletRequest request, TssLoginDetails loginDetails) {
		TssSession.getNewSess(request, -1);
		TssSession.setAttribute(request, loginDetails);
	}

}
