package kr.co.jinwoosi.clfd.framework.security.handler;

import kr.co.jinwoosi.clfd.framework.security.model.User;
import kr.co.jinwoosi.clfd.framework.security.model.UserSearch;
import kr.co.jinwoosi.clfd.framework.security.service.UserService;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@Component("loginFailureHadler")
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Resource(name = "userService")
    private UserService userService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2)
            throws IOException, ServletException {

        UserSearch userSearch = new UserSearch();
        userSearch.setUserLoginId(request.getParameter("userLoginId"));
        User user = userService.select(userSearch);

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpSession session = httpRequest.getSession();
        String URL = (String) session.getAttribute("loginRequestURL");

        int error = -1; // 기본 로그인 실패 원인은 아이디/비밀번호 오류
        if (user == null) {
            error = -1;
        } else {
            if (user.getFailCnt() > 5) { // 로그인 실패 횟수가 5회가 이상인 경우
                error = -2;
            }
            if (user.getAuthStCd() == "0") {
                error = -3;
            }
        }
        if (("login").equals(URL)) {
            response.sendRedirect("/login.do?error=" + error);
            return;
        } else {
            response.sendRedirect("/login/loginForm.mng?path=" + httpRequest.getParameter("path") + "&error=" + error);
            return;
        }
    }

}
