package com.its.web.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@Slf4j
@Service
public class WebLoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String key = "LoginFail";
        String message = "계정을 찾을 수 없습니다.";
        if (exception instanceof AuthenticationServiceException) {
            message ="시스템에 오류가 발생했습니다.";
        }
        else if (exception instanceof UsernameNotFoundException) {
            message = "아이디를 찾을 수 없습니다.";
        }
        else if (exception instanceof BadCredentialsException) {
            message = "아이디 또는 비밀번호가 일치하지 않습니다.";
        }
        else if (exception instanceof DisabledException) {
            message = "현재 사용할 수 없는 계정입니다.";
        }
        else if (exception instanceof LockedException) {
            message = "현재 잠긴 계정입니다.";
        }
        else if (exception instanceof AccountExpiredException) {
            message = "이미 만료된 계정입니다.";
        }
        else if (exception instanceof CredentialsExpiredException) {
            message = "비밀번호가 만료된 계정입니다.";
        }
        log.error("{}: {}, {}", key, message, request.getParameter("username"));
        request.setAttribute(key, message);
        message = URLEncoder.encode(message, "UTF-8");
        response.sendRedirect("/phits?LoginFail=" + message);
//        request.getRequestDispatcher("/phits").forward(request, response);
    }
}
