package gov.va.med.authentication.kernel.ccow;

import org.apache.log4j.Logger;
import org.apache.log4j.Level;

import gov.va.med.authentication.kernel.KaajeeException;
import gov.va.med.authentication.kernel.VistALogon;
import gov.va.med.authentication.kernel.LoginUserInfoVO;

/**
 * @author VHIT Security and Other Common Services (S&OCS)
 * @version 1.1.0.007
 */
public class VistaTokenValidator {
	
	private static Logger logger = Logger.getLogger(VistaTokenValidator.class);

	private CcowEnv ccowEnv;

	public VistaTokenValidator(CcowEnv ccowEnv) {
		this.ccowEnv = ccowEnv;
	}

	public boolean hasVAContext() {
		return (null != ccowEnv.getCurrentCommonContext()) ;
	}
	public LoginUserInfoVO validate() throws KaajeeException {
		
		LoginUserInfoVO userInfo = null;
		if (!hasVAContext()) return userInfo; // null
		CommonContextMap vaContext = ccowEnv.getCurrentCommonContext();
		// get token to validate
        String vistaToken = vaContext.getContextItem(CommonContextMap.VHA_CCOW_LOGON_TOKEN);
        // obtain vista station for which ccow user context currently exists
        // vistalogon = <domain name>^<station>
        // need station to validate token
        String vistaLogon = vaContext.getContextItem(CommonContextMap.VHA_CCOW_LOGON_DOMAIN);
        boolean validValues = vistaToken != null && 
        					  vistaToken.length() > 0 &&
        					  vistaLogon != null &&
        					  vistaLogon.split("\\^").length > 1; // "domainName^institution#"
        if (!validValues)
        	throw new KaajeeException("invalid user context in VA context");
        
        String [] array = vistaLogon.split("\\^");
        String institution = array[1];
        
        String clientIP = ccowEnv.getClientIPAddr();
        userInfo = VistALogon.getLoginUserInfo(vistaToken, institution, clientIP);
        
        if (userInfo != null) {
			if (logger.isEnabledFor(Level.DEBUG)) {
				logger.debug("successfully validated the user using ccow sso:"  + userInfo);
			}
        }
		return userInfo;
	}

}
