package gov.va.med.authentication.kernel;

import java.util.StringTokenizer;

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

import gov.va.med.vistalink.adapter.cci.VistaLinkAppProxyConnectionSpec;
import gov.va.med.vistalink.adapter.cci.VistaLinkConnection;
import gov.va.med.vistalink.adapter.cci.VistaLinkConnectionSpec;
import gov.va.med.vistalink.adapter.cci.VistaLinkDuzConnectionSpec;
import gov.va.med.vistalink.rpc.RpcRequest;
import gov.va.med.vistalink.rpc.RpcRequestFactory;
import gov.va.med.vistalink.rpc.RpcResponse;

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

	public static LoginUserInfoVO getLoginUserInfo(String vistaToken, String institution, String clientIp) 
		throws KaajeeException {
		LoginUserInfoVO userInfo = null;
		VistaLinkConnectionSpec connSpec = new VistaLinkAppProxyConnectionSpec(institution, "KAAJEE,PROXY");
		VistaLinkConnection conn = LoginControllerUtils.getVistaLinkConnection(institution,connSpec);
		userInfo = LoginUserInfoVOAssembler.getLoginUserInfoCCOW(conn, institution, clientIp, vistaToken);
		if (userInfo == null) throw new KaajeeException("no LoginUserInfoVo fount");
		
		return userInfo;
	}

	public static String getKernelCcowToken(String institution, String duz, String clientIP) {
		VistaLinkConnection        myConnection = null;
        VistaLinkDuzConnectionSpec duzConnSpec   = null;
        String                     ccowToken    = null; //$NON-NLS-1$
        try {
        	duzConnSpec   = new VistaLinkDuzConnectionSpec(institution, duz);
            myConnection = LoginControllerUtils.getVistaLinkConnection(institution, duzConnSpec);
            ccowToken = getKernelCcowToken(myConnection, clientIP);
        } catch (Exception e) {
			if (logger.isEnabledFor(Level.ERROR)) {
				logger.debug("failed to obtain ccowToken");
			}
            ccowToken = null;
        }
        finally
        {
            // we're done with M connections now.
            LoginControllerUtils.closeVistaLinkConnection(myConnection);
        }
        
        return ccowToken;        
	}

	public static String getSecureCcowPasscode(String institution, String duz) {
        VistaLinkConnection myConnection = null;
        VistaLinkDuzConnectionSpec duzConnSpec   = null;
        String              ccowpasscode = null; //$NON-NLS-1$
        try
        {
        	duzConnSpec   = new VistaLinkDuzConnectionSpec(institution, duz);
        	myConnection = LoginControllerUtils.getVistaLinkConnection(institution, duzConnSpec);       	
            ccowpasscode = getSecureCcowPasscode(myConnection);
        } catch (Exception e) {
			if (logger.isEnabledFor(Level.ERROR)) {
				logger.debug("failed to obtain ccowpasscode");
			}
        	ccowpasscode = null;
        } finally {
            // we're done with M connections now.
            LoginControllerUtils.closeVistaLinkConnection(myConnection);
        }
        
        return ccowpasscode;
	}

	private static String getKernelCcowToken(VistaLinkConnection myConnection, String clientIP) {
        RpcRequest  vReq  = null;
        RpcResponse vResp = null;
        String      rVal  = ""; //$NON-NLS-1$

        logger.debug("START getKernelCcowToken."); //$NON-NLS-1$

        try
        {
            vReq = RpcRequestFactory.getRpcRequest();

            vReq.setRpcContext("XUS KAAJEE WEB LOGON");
            vReq.setRpcClientTimeOut(600);
            vReq.setTimeOut(5000);
            vReq.setUseProprietaryMessageFormat(true);
            vReq.setRpcName("XUS KAAJEE GET CCOW TOKEN");
            vReq.getParams().setParam(1, "string", clientIP);

            vResp = myConnection.executeRPC(vReq);

            rVal = vResp.getResults();
        }
        catch (Exception ex)
        {
            logger.error("Failed to retrieve Kernel CCOW token. " + "XUS GET CCOW TOKEN", ex); //$NON-NLS-1$ //$NON-NLS-2$
        }
        
        logger.debug("kernelccowtoken = [" + rVal + "]"); //$NON-NLS-1$ //$NON-NLS-2$
        
        logger.debug("END getKernelCcowToken.");                 //$NON-NLS-1$
        
        return rVal;
	}

	private static String getSecureCcowPasscode(VistaLinkConnection myConnection) {
        RpcRequest  vReq      = null;
        RpcResponse vResp     = null;
        String      returnVal = ""; //$NON-NLS-1$

        logger.debug("START getSecureCcowPasscode."); //$NON-NLS-1$

        try
        {
            vReq = RpcRequestFactory.getRpcRequest();

            vReq.setRpcContext("XUS SIGNON"); //$NON-NLS-1$
            vReq.setRpcClientTimeOut(600);
            vReq.setTimeOut(5000);
            vReq.setUseProprietaryMessageFormat(true);
            vReq.setRpcName("XUS CCOW VAULT PARAM"); //$NON-NLS-1$

            vResp = myConnection.executeRPC(vReq);

            StringTokenizer st = new StringTokenizer(vResp.getResults(), "\n"); //$NON-NLS-1$

            if (st.countTokens() == 2)
            {
                returnVal = st.nextToken() + st.nextToken();
            }
            // else return "", and writing user context will fail.
        }
        catch (Exception ex)
        {
            logger.error("Failed to retrieve CCOW passcode. " + "XUS GET CCOW TOKEN", ex); //$NON-NLS-1$ //$NON-NLS-2$
        }

        logger.debug("END getSecureCcowPasscode."); //$NON-NLS-1$
        
        return returnVal;
	}

}
