package gov.va.med.cds.persistence.hibernate.rpc;

import java.util.Iterator;
import java.util.Map;

public class RpcParamStringBuilder extends
		AbstractBaseRpcParamStringBuilder {
	
	@Override
	public String build(Map<String, String> queryParams) {
		StringBuffer sbParams = new StringBuffer();

        Iterator<String> iter = queryParams.keySet().iterator();
        while ( iter.hasNext() )
        {
            String paramName = iter.next();
            if(!rpcUnusedParamNames.contains(paramName))
            {
            	
            	String paramValue =  queryParams.get( paramName );
            	if("command".equals(paramName)){
            		paramValue = getCommandParamValue();
            	}
            	if("pid".equals(paramName)){
            		if(prependFunctionToPatient()){
            			paramValue = getFunctionCall()+paramValue;
            			//we are adding an VistA System function call and do not want to surround the value in escaped quotes as we do the paramName
            			//sbParams.append( String.format( "A:ARGS(\"%s\")=%s", paramName, paramValue) );
            			sbParams.append( String.format( getArgWithFunctionFormat(), paramName, paramValue) );
            			if ( iter.hasNext() )
                    	{
                    		sbParams.append( "|" );
                    	}
            			continue;
            		}	
            	}
            	if(("stop").equals(paramName)||("start").equals(paramName))
            	{
            		if(addFunctionToDate())
            		{
            			//hardcoding this fix around date range - RPC expects a fileman date - which will transform yyyyMMddHHmmss (20140101141609 into 3140101.141609) to a fileman date
            			//paramValue = "$$HL7TFM^XLFDT("+paramValue+")";
            			paramValue = getFunctionCall()+"("+paramValue+")";
            			//sbParams.append( String.format( "A:FILTER(\"%s\")=%s", paramName, paramValue) );
            			sbParams.append( String.format( getArgWithFunctionFormat(), paramName, paramValue) );
            			if ( iter.hasNext() )
            			{
            				sbParams.append( "|" );
            			}
            			continue;
            		}
            	}
            	if("server".equals(paramName)){
            		paramName=getServerParamName();
            	}
            	
            	
            	//sbParams.append( String.format( "A:ARGS\"%s\")=\"%s\"", paramName, paramValue) );
            	sbParams.append( String.format( getArgFormat(), paramName, paramValue) );

            	if ( iter.hasNext() )
            	{
            		sbParams.append( "|" );
            	}
            }
        }

       
        sbParams.append( this.vistaFixedEnvParam );

        return sbParams.toString();
	}


	@Override
	public String getRpcPatientArgName() {
		return this.patientIdParamName;
	}


}
