package com.zcxk.security;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.zcxk.model.AjaxMessage;
import com.zcxk.security.smsCode.SmsCodeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import com.zcxk.security.exception.SecurityException;

@Component("myAuthenctiationFailureHandler")
public class MyAuthenctiationFailureHandler extends SimpleUrlAuthenticationFailureHandler {


    @Autowired
    private ObjectMapper objectMapper;

    /* (non-Javadoc)
     * @see org.springframework.security.web.authentication.AuthenticationFailureHandler#onAuthenticationFailure(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {

        logger.info("登录失败:{}",exception.getCause());

        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json;charset=UTF-8");
        ObjectMapper objectMapper = new ObjectMapper();
        if (exception instanceof SecurityException) {
            SecurityException securityException = (SecurityException) exception;
            AjaxMessage ajaxMessage = new AjaxMessage<>(securityException.getStatus(),securityException.getMessage(),null);
            response.getWriter().write(objectMapper.writeValueAsString(ajaxMessage));
        } else if(exception instanceof SmsCodeException){
            SmsCodeException smsCodeException = (SmsCodeException) exception;
            AjaxMessage ajaxMessage = new AjaxMessage<>(smsCodeException.getStatus(),exception.getMessage(),null);
            response.getWriter().write(objectMapper.writeValueAsString(ajaxMessage));
        }else {
            AjaxMessage ajaxMessage = new AjaxMessage<>(-100,exception.getMessage(),null);
            response.getWriter().write(objectMapper.writeValueAsString(ajaxMessage));
        }


    }

}
