

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


import java.util.Date;

import javax.ws.rs.core.MultivaluedMap;

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


/**
 * This class uses an XSLT style-sheet to generate the filter from the incoming request.
 */
public class RecordIdentifierReadRequestXsltFilterBuilder
    extends
        AbstractBaseFilterBuilder
{

    Document buildRequestParamsDocument( String filter, String domain, String recordIdentifier, MultivaluedMap<String, String> additionalParams )
    {
        Document filterDocument = DocumentHelper.createDocument( DocumentHelper.createElement( "requestData" ) );
        filterDocument.getRootElement().add( DocumentHelper.createElement( "filterId" ).addText( filter ) );
        filterDocument.getRootElement().add( DocumentHelper.createElement( "domainEntryPoint" ).addText( domain ) );
        filterDocument.getRootElement().add( DocumentHelper.createElement( "recordIdentifier" ).addText( recordIdentifier ) );

        for ( String key : additionalParams.keySet() )
        {
            if ( StringUtils.hasLength( additionalParams.getFirst( key ) ) )
            {
                if ( !key.startsWith( "_" ) ) // ignore any query parameters that start with an underscore character.
                {
                    if ( STANDARD_FILTER_PARAMS.contains( key ) )
                    {
                        if ( key.equals( "clientInitiationTime" ) )
                        {
                            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
                        {
                            filterDocument.getRootElement().add( DocumentHelper.createElement( key ).addText( additionalParams.getFirst( key ) ) );
                        }
                    }
                }
            }
        }

        return filterDocument;
    }


}
