package com.style24.admin.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.admin.biz.service.TsaLoginService;
import com.style24.admin.support.security.TsaLoginDetails;
import com.style24.admin.support.security.session.TsaSession;

import lombok.extern.slf4j.Slf4j;

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

	@Autowired
	private TsaLoginService loginService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		// 로그인 상세 정보
		TsaLoginDetails loginDetails = (TsaLoginDetails)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, TsaLoginDetails loginDetails) {
		TsaSession.getNewSess(request, -1);
		TsaSession.setAttribute(request, loginDetails);
	}

}
