package com.style24.front.support.interceptor;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Calendar;
import java.util.List;

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.beans.factory.annotation.Value;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.style24.front.biz.service.TsfLoginService;
import com.style24.front.support.env.TsfConstants;
import com.style24.front.support.security.TsfLoginDetails;
import com.style24.front.support.security.session.TsfSession;
import com.style24.persistence.domain.Login;
import com.style24.persistence.domain.PersistentToken;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.web.util.GagaCookieUtil;
import com.gagaframework.web.util.GagaCryptoUtil;
import com.gagaframework.web.util.GagaDateUtil;

/**
 * 자동로그인 RememberMe 선처리
 *
 * @author gagamel
 * @since 2020. 9. 11
 */
@Component
@Slf4j
public class TsfRememberMeInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private TsfLoginService loginService;

	@Value("${has-ssl}")
	private String hasSsl;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		// RememberMe Cookie
		String ckRememberMe = GagaCookieUtil.getCookie(request, TsfConstants.CK_PREFIX + "_remember-me");

		if (!TsfSession.getFrontGb().equals("P") && !TsfSession.isLogin() && StringUtils.isNotBlank(ckRememberMe)) {
			// 로그인유지토큰 조회
			PersistentToken rememberToken = loginService.getPersistentToken(ckRememberMe);

			if (rememberToken != null) {
				Login loginParam = new Login();
				loginParam.setCustId(rememberToken.getCustId());
				Login loginInfo = loginService.getLoginCheckInfo(loginParam);

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

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

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

				// 세션 생성
				List<SimpleGrantedAuthority> authorities = new ArrayList<>();
				authorities.add(new SimpleGrantedAuthority(loginInfo.getCustGb()));
				this.createSession(request, new TsfLoginDetails(loginInfo, authorities));

//				Date expiry = new Date(System.currentTimeMillis() + (1000 * TsfConstants.REMEMBER_ME_LIMIT));

//				<<<<<<< 2021-09-12 일 자동로그인 과련 이슈로 GagaDateUtil.getOffsetDate 변경처리 시작
//				String expiry = GagaDateUtil.getOffsetDate(TsfConstants.REMEMBER_ME_LIMIT);
//				==============================================================================
				Calendar cal = Calendar.getInstance();
				cal.add(Calendar.DATE, TsfConstants.REMEMBER_ME_LIMIT);
				String expiry = new SimpleDateFormat("yyyyMMddHHmmss").format(cal.getTime());
//				>>>>>>> 2021-09-12 일 자동로그인 과련 이슈로 GagaDateUtil.getOffsetDate 변경처리 끝

//				String md5HexToken = GagaCryptoUtil.encryptMD5(token.getCustNo() + ":" + GagaDateUtil.getDate(expiry, "yyyyMMddHHmmss") + ":" + TsfSession.getSessionId());
				String md5HexToken = GagaCryptoUtil.encryptMD5(rememberToken.getCustNo() + ":" + expiry + ":" + TsfSession.getSessionId());
				String newRemembermeToken = Base64.getEncoder().encodeToString((TsfConstants.REMEMBER_ME_KEY + ":" + md5HexToken).getBytes());

				// RememberMe 쿠키 생성
				if(Boolean.parseBoolean(hasSsl)) {
					GagaCookieUtil.setSecureCookie(response, TsfConstants.CK_PREFIX + "_remember-me", newRemembermeToken, TsfConstants.REMEMBER_ME_LIMIT_SECONDS);
				}else {
					GagaCookieUtil.setCookie(response, TsfConstants.CK_PREFIX + "_remember-me", newRemembermeToken, TsfConstants.REMEMBER_ME_LIMIT_SECONDS);
				}

				// 로그인유지토큰 갱신
				loginService.updatePersistentToken(rememberToken.getCustNo(), rememberToken.getRemembermeToken(), newRemembermeToken, expiry);
			}
		}

		return super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
		ModelAndView modelAndView) throws Exception {
		// Do nothing
	}

	/**
	 * 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);
	}

}
