package com.mx.dla.configuration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

@Component
public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	
	@Autowired
	private UsuarioDAO usuarioDAO;
	
	protected Logger logger =  LoggerFactory.getLogger("app");
	
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws ServletException, IOException {
    	
    	logger.info("Login successful: " + authentication.getName() + " at " + LocalDateTime.now());

        usuarioDAO.actualizaEstadoSesion(0, authentication.getName());
    	
    	String ipAddress = request.getHeader("X-FORWARDED-FOR");
        if (ipAddress == null || ipAddress.isEmpty()) {
            ipAddress = request.getRemoteAddr();
        }
        ipAddress = ipAddress.split(",")[0];
        
        String userAgent = request.getHeader("User-Agent");
        
        usuarioDAO.insertaBitacora("LogIn Exitoso", authentication.getName(), ipAddress, userAgent);

        getRedirectStrategy().sendRedirect(request, response, "/inicio.action");
    }
}

