package kr.co.uplus.ez.api.login;

import java.io.IOException;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import kr.co.uplus.ez.api.login.dto.AuthUser;
import kr.co.uplus.ez.common.data.ApiResponseCode;
import kr.co.uplus.ez.common.data.Const;
import kr.co.uplus.ez.config.SecurityConfig;

/**
 * 로그인에 실패하면 호출되는 기본 핸들러는 SimpleUrlAuthenticationFailureHandler 클래스이다.
 */
public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {

	@SuppressWarnings("unused")
	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private LoginService svc;

	public LoginFailureHandler() {
	}

	public LoginFailureHandler(String loginFailUrl) {
		super(loginFailUrl);
	}

	@Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
    		AuthenticationException exception) throws IOException, ServletException {
		process(request, response, exception);
		super.onAuthenticationFailure(request, response, exception);
    }

	/*
	public ResultCode process(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
		String userId = request.getParameter(SecurityConfig.LOGIN_ID_PARAM);
		if (userId == null)
			userId = (String) request.getAttribute(SecurityConfig.LOGIN_ID_PARAM);
		AuthUser user = (AuthUser) request.getAttribute(Const.KEY_LOAD_USER);
		ResultCode resultCode = ResultCode.SE_UNKNOWN;

    	if (exception instanceof BadCredentialsException) {
    		resultCode = ResultCode.CE_ID_PWD;
    		if (user != null) { // 없는 ID면 user == null 이고 PWD 불일치면 user != null 이다
    			int failCnt = svc.increaseFailCount(userId);
    			if (failCnt >= Const.MAX_LOGIN_FAIL) {
    				svc.setUserStatus(userId, UserStatus.LOCK);
    				resultCode = ResultCode.CE_TO_LOCK;
    			}
    		}
    	}
    	else if (exception instanceof DisabledException) {
    		resultCode = ResultCode.SS_NOT_USE;
    	}
    	else if (exception instanceof LockedException) {
    		resultCode = ResultCode.SS_LOCK;
    	}
//    	else if (exception instanceof CredentialsExpiredException) {
//    		resultCode = ResultCode.SS_PWD_EXPIRE;
//    	}

    	return resultCode;
	}
*/
	public ApiResponseCode process(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
		String userId = request.getParameter(SecurityConfig.LOGIN_ID_PARAM);
 		if (userId == null) {
			userId = (String) request.getAttribute(SecurityConfig.LOGIN_ID_PARAM);
 		}
		AuthUser user = (AuthUser) request.getAttribute(Const.KEY_LOAD_USER);
		ApiResponseCode resultCode = ApiResponseCode.SE_UNKNOWN;

    	if (exception instanceof BadCredentialsException) {
    		resultCode = ApiResponseCode.CE_ID_PWD;
    		if (user != null) { // 없는 ID면 user == null 이고 PWD 불일치면 user != null 이다
    			int failCnt = svc.increaseFailCount(userId);
    			if (failCnt >= Const.MAX_LOGIN_FAIL) {
    				svc.setUserStatus(userId, "02");
    				resultCode = ApiResponseCode.CE_TO_LOCK;
    			}
    		}
    	}
    	else if (exception instanceof DisabledException) {
    		resultCode = ApiResponseCode.SS_NOT_USE;
    	}
    	else if (exception instanceof LockedException) {
    		resultCode = ApiResponseCode.SS_NOT_USE;
    	}
//    	else if (exception instanceof CredentialsExpiredException) {
//    		resultCode = ResultCode.SS_PWD_EXPIRE;
//    	}

    	return resultCode;
	}
}
