package com.mx.dla.configuration;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Objects;

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.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Component;

import com.mx.dla.admin.daos.UsuarioDAO;

@Component
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
	
	protected Logger logger =  LoggerFactory.getLogger("app");
	
	@Autowired
	private UsuarioDAO usuarioDAO;
	
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        logger.info("Login failed: " + exception.getMessage() + " at " + LocalDateTime.now());
        
        String ipAddress = request.getHeader("X-FORWARDED-FOR");
        if (ipAddress == null || ipAddress.isEmpty()) {
            ipAddress = request.getRemoteAddr();
        }
        ipAddress = ipAddress.split(",")[0];
        
        String username = request.getParameter("username");
        String userAgent = request.getHeader("User-Agent");
        
        if (exception.getClass().isAssignableFrom(DisabledException.class) || 
        		exception.getClass().isAssignableFrom(SessionAuthenticationException.class)) {
        	super.setDefaultFailureUrl("/index.jsp?login_error=2");
        } else {
        	super.setDefaultFailureUrl("/index.jsp?login_error=1");
        }
        if(Objects.nonNull(username)) {
        	usuarioDAO.insertaBitacora("LogIn Fallido", username, ipAddress, userAgent);
        } else {
        	usuarioDAO.insertaBitacora("LogIn Fallido", "NO USER", ipAddress, userAgent);
        }
        super.onAuthenticationFailure(request, response, exception);
    }
}

