/********************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ********************************************************************/
package gov.va.med.esr.ui.common.action;

// Java classes
import gov.va.med.esr.common.model.security.ESRUserPrincipal;
import gov.va.med.esr.ui.ApplicationConstants;

import gov.va.med.fw.security.SecurityContext;
import gov.va.med.fw.security.SecurityContextHelper;
import gov.va.med.fw.security.UserCredentials;
import gov.va.med.fw.security.InvalidSecurityCodeException;
import gov.va.med.fw.util.StringUtils;

import javax.security.auth.login.CredentialExpiredException;
import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.Validate;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * A command class to process a log on action in an logon.jsp page. LogonAction
 * uses EDBLoginManager to authenticate the user.
 *
 * @author DNS   LEV
 * @author Muddaiah Ranga
 * @version: 1.0,3.0
 */
public class LogonAction extends AbstractLogonAction
{
     public LogonAction()
     {
     	super();
     }

    /**
     * Performs a logon action triggered in an index.jsp page. A generic
     * exception is thrown to allow a custom exception to be registered in a
     * confiuration file.
     *
     * @param mapping
     *            An action mapping
     * @param form
     *            A form bean
     * @param request
     *            A http request from an index.jsp page
     * @param response
     *            A http response to stream data to a next page
     * @return An action forward class encapsulating information about a next
     *         page
     * @throws java.lang.Exception Thrown if failed to process
     */
    public ActionForward logon(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception
	{

    	UserInfoForm userForm = (form instanceof UserInfoForm) ? (UserInfoForm) form : null;
        //default forward
        ActionForward forward = mapping.getInputForward();
        
        if (userForm == null) {
        	return forward;
        }
        
    	//CCR13343 SSOi integration
        userForm.init(request, getUserAdminService().isSsoEnforced(), getUserAdminService().getSsoUsername());
        Validate.notNull("Invalid form bean configured for this action.");

        UserCredentials userCredentials = userForm.getUserCredentials();


        try {

	        if (userCredentials.getUserID() == null)
	        	throw new LoginException("Login failed due to NULL network_id in http header");

	        // Log the user out first and login as anonymous with entered id as logical id
	        processSignout(request, userCredentials.getUserID().toUpperCase());

            //Validate security code requirements
            getUserAdminService().verifySecurityCode(
                    userCredentials.getUserID(),userCredentials.getSecurityCode());

            //perform the actual authentication
            forward = doAuthentication(mapping, request,userCredentials);

        }catch(InvalidSecurityCodeException e) {
            userForm.reset(mapping,request);
            userForm.setSecurityCodeRequired(true);
            if (StringUtils.isEmpty(userCredentials.getSecurityCode())){
                //required error message
                addActionMessageForField(request,MSG_SECURITY_CODE_REQUIRED,FLD_SECURITY_CODE);
            }
            else {
                //invalid error message
                addActionMessageForField(request,MSG_SECURITY_CODE_INVALID,FLD_SECURITY_CODE);
            }
        }
        catch(CredentialExpiredException ceEx)
        {
            userForm.reset(mapping,request);
            log.error("Credential expired for user ",ceEx);
            addActionMessage(request,getActionMessage(ceEx));
            forward = mapping.findForward(CHANGE_PASSWORD_DISPLAY);
        }
        catch(LoginException e)
        {
            userForm.reset(mapping,request);
            log.error("Authentication failed for user ",e);
            addActionMessage(request,getActionMessage(e));
            forward = mapping.findForward(FORWARD_FAILURE);
        }

        return forward;
    }

    public ActionForward home(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        //If the user doesn't have any privileges except login
        //return back to the login page
        return mapping.findForward(HOME_PAGE);
    }
    /**
     * Perform authentication by delegating authentication request to the
     * defined AuthenticationManager.
     *
     * @param mapping Struts action mapping for this action
     * @param request The Http Request
     * @param userCredentials user information
     */
    private ActionForward doAuthentication(ActionMapping mapping,
            HttpServletRequest request, UserCredentials userCredentials) throws LoginException
    {
       	establishSecurityContext(mapping,request,userCredentials);
    	SecurityContext securityContext = SecurityContextHelper.getSecurityContext();
    	ESRUserPrincipal user = (ESRUserPrincipal)securityContext.getUserPrincipal();
    	//CCR13343
		/*if(user.isPasswordChangeWarningDays())
		{
			return mapping.findForward(CHANGE_PASSWORD);
		}*/
        return mapping.findForward(HOME_PAGE);
    }
}