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

import java.io.IOException;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.style24.front.biz.service.TsfLoginService;
import com.style24.front.support.security.TsfLoginDetails;

import lombok.extern.slf4j.Slf4j;

/**
 * RememberMe를 통한 로그인 성공 시 호출되는 Handler
 * 
 * @author gagamel
 * @since 2020. 9. 11
 */
@Slf4j
public class TsfRememberMeSuccessHandler implements AuthenticationSuccessHandler {

	@Autowired
	private TsfLoginService loginService;

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

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

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

		// 로그인이력 생성
		loginService.createLoginHistory(custNo);

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

//		String isApp = FoSession.getAttribute("isApp");
//		if ("true".equals(isApp)) {
//			customerService.giveFirstAppDownPoint(loginDetails.getUsername());
//		}

		String returnUrl = request.getRequestURL().toString();
		log.info("returnUrl: {}", returnUrl);

		if (StringUtils.isBlank(returnUrl)) {
			returnUrl = "/";
		}

		response.sendRedirect(returnUrl);
	}

	/**
	 * Session 생성
	 * @param request - HttpServletRequest
	 * @param loginDetails - 로그인 상세 정보
	 */
	private void createSession(HttpServletRequest request, TsfLoginDetails loginDetails) {
		HttpSession session = request.getSession(true);
		session.setMaxInactiveInterval(1800);
		session.setAttribute("session", loginDetails);
	}

}
