package gov.va.med.edp.springframework.security.ui.vistalink;

import gov.va.med.edp.springframework.security.providers.vistalink.VistaAuthenticationToken;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.ui.webapp.AuthenticationProcessingFilter;

import javax.servlet.http.HttpServletRequest;

public class VistaAuthenticationProcessingFilter extends AuthenticationProcessingFilter {

    public static final String STATION_NUMBER_KEY = "j_stationNumber";
    public static final String ACCESS_CODE_KEY = "j_access";
    public static final String VERIFY_CODE_KEY = "j_verify";

    public Authentication attemptAuthentication(HttpServletRequest request) throws AuthenticationException {
        String stationNumber = obtainStationNumber(request);
        String accessCode = obtainAccessCode(request);
        String verifyCode = obtainVerifyCode(request);
        String remoteAddress = obtainRemoteAddress(request);

        if (accessCode == null) {
            accessCode = "";
        }

        if (verifyCode == null) {
            verifyCode = "";
        }

//        accessCode = accessCode.trim();

        VistaAuthenticationToken authRequest = new VistaAuthenticationToken(stationNumber, accessCode, verifyCode, remoteAddress);

        // Place the last username attempted into HttpSession for views
//        request.getSession().setAttribute(ACEGI_SECURITY_LAST_USERNAME_KEY, accessCode);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        logger.debug("Attempting authentication with token: " + authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }

    protected String obtainStationNumber(HttpServletRequest request) {
        return request.getParameter(STATION_NUMBER_KEY);
    }

    protected String obtainAccessCode(HttpServletRequest request) {
        return request.getParameter(ACCESS_CODE_KEY);
    }

    protected String obtainVerifyCode(HttpServletRequest request) {
        return request.getParameter(VERIFY_CODE_KEY);
    }

    protected String obtainRemoteAddress(HttpServletRequest request) {
        return request.getRemoteAddr();
    }
}
