
package gov.va.med.repositories.fpds.filter;

import java.util.Date;
import java.util.List;

import javax.ws.rs.core.MultivaluedMap;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.util.StringUtils;

/**
 * This class uses an XSLT style-sheet to generate the filter from the incoming request.
 */
public class GenericReadRequestXsltFilterBuilder extends AbstractBaseFilterBuilder
{
  
     Document buildRequestParamsDocument( String filter, String domain, String patient, MultivaluedMap<String, String> additionalParams )
    {
    	Document filterDocument = DocumentHelper.createDocument( DocumentHelper.createElement( "requestData" ) );
        filterDocument.getRootElement().add( DocumentHelper.createElement( "filterId" ).addText( filter ) );
        String icn = additionalParams.getFirst( ICN );
        if(icn != null){
        	filterDocument.getRootElement().add( DocumentHelper.createElement( "patientId" ).addText( icn) );
        }
        filterDocument.getRootElement().add( DocumentHelper.createElement( "domainEntryPoint" ).addText( domain) );
        filterDocument.getRootElement().add(DocumentHelper.createElement( "additionalParams" ));
        
        for(String key : additionalParams.keySet())
        {
            if(  StringUtils.hasLength( additionalParams.getFirst( key ) ) )
            {
            	 // ignore any query parameters that start with an underscore character or path params that become main elements in the filter or queryParames unused in filter such as templateId.
            	if(!key.startsWith( "_" ) && !key.equals("filterId") && !key.equals("templateId") && !key.equals(ICN))
                {
                    if(STANDARD_FILTER_PARAMS.contains( key ))
                    {
                        if(key.equals("clientRequestInitiationTime")){
                        	String clientInitiationTime = ( String )additionalParams.getFirst( key );
                        	if ( !StringUtils.hasText( clientInitiationTime ) )
                            {
                        		filterDocument.getRootElement().add( DocumentHelper.createElement( "clientRequestInitiationTime" ).addText( DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format( new Date() ) ) );
                            }
                            else
                            {
                            	filterDocument.getRootElement().add( DocumentHelper.createElement( "clientRequestInitiationTime" ).addText( clientInitiationTime ) );
                            }
                        }
                        else if ( key.equals( EX_AI ) && StringUtils.hasLength( icn ) )
                        {
                        	String[] content = null;
                        	List<String> excludeIds = additionalParams.get( EX_AI );
                            for ( String excludeId : excludeIds )
                            {
                                content = excludeId.split( SEPARATOR );
                                
                                if ( content != null && content.length > 1 )
                                {   
                                	Element excludedId = DocumentHelper.createElement( "excludedId" );
                                    if ( content.length > 1 )
                                    {
                                        excludedId.add( DocumentHelper.createElement( "excludedAssigningFacility" ).addText( content[1] ) );
                                    }
                                    if ( content.length > 2 )
                                    {
                                        excludedId.add( DocumentHelper.createElement( "excludedAssigningAuthority" ).addText( content[2] ) );
                                    }
                                        
                                    if ( content[0] != null || content[0].length() > 0 ){
                                       excludedId.add( DocumentHelper.createElement( "excludedIdentifier" ).addText( content[0] ) );
                                    }
                                    
                           
                                   filterDocument.getRootElement().add( excludedId );
                                }  

                            }

                        }
                        else if ( key.equals( RS_ID ) && !StringUtils.hasLength( icn ) )
                        {
                        	String[] content = null;
                        	List<String> dfnList = additionalParams.get( RS_ID );
                            for ( String dfn : dfnList )
                            {

                                content = dfn.split( SEPARATOR );
                                Element el = DocumentHelper.createElement( "resolvedIdentifier" );
                                if ( content != null && content.length > 0 )
                                {
                                    if ( content[0] != null || content[0].length() > 0 )
                                    {
                                        el.add( DocumentHelper.createElement( "identifier" ).addText( content[0] ) );

                                        if ( content.length > 1 )
                                        {
                                            el.add( DocumentHelper.createElement( "assigningFacility" ).addText( content[1] ) );
                                        }
                                        if ( content.length > 2 )
                                        {
                                            el.add( DocumentHelper.createElement( "assigningAuthority" ).addText( content[2] ) );
                                        }
                                    }

                                }
                                filterDocument.getRootElement().add( el );

                            }

                        }
                        else{
                        	filterDocument.getRootElement().add( DocumentHelper.createElement( key).addText( additionalParams.getFirst( key ) ) );
                        }
                    }
                    else
                    {
                    	filterDocument.getRootElement().element( "additionalParams" ).add( DocumentHelper.createElement( "entry" ).addAttribute( "key", key )
                                        .addAttribute( "value", additionalParams.getFirst(key) ) );
                    }
                }
            }
        }
        
        return filterDocument;
    }
}
