/**
 * 
 */


package gov.va.med.cds.response;


import gov.va.med.cds.filter.CdsFilterInterface;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;


/**
 * @author DNS   TALBOM
 *
 */
public class NonSequencePatientIdentifierDocumentBuilder
    extends
        DefaultPatientIdentifierDocumentBuilder
{

    @Override
    public Document createPatientWithIdentifiersDocument( CdsFilterInterface filter, String templateId, String requestId )
    {
        Document result = this.clinicalDataResponse.buildEmptyClinicalDocumentWithPatient( templateId, requestId );
        Element patient = this.clinicalDataResponse.getPatientElement( result );
        List<Element> resultantIdentifiers = filter.getResolvedIdentifiers();

        Element nationalId = filter.getNationalId();
        if ( nationalId != null )
        {
            //patient.addElement( "requestedNationalId", nationalId.getText() );
            this.clinicalDataResponse.addRequestedNationalId( result, nationalId.getText() );
            for ( Element resultantIdentifier : resultantIdentifiers )
            {
                patient.addElement( "resultantIdentifiers" ).add( createIdentifierCollectionElement( "resultantIdentifier", resultantIdentifier ) );
            }
        }
        else
        {
            Element edipiId = filter.getEdipi();
            if ( edipiId != null )
            {
                patient.add( createIdentifierCollectionElement( "requestedEdiPi", edipiId ) );
                patient.addElement( "resultantIdentifiers" ).add( createIdentifierCollectionElement( "resultantIdentifier", edipiId ) );
            }
            else
            {

                for ( Element resultantIdentifier : resultantIdentifiers )
                {
                    patient.addElement( "requestedResolvedIdentifiers" ).add(
                                    createIdentifierCollectionElement( "requestedResolvedIdentifier", resultantIdentifier ) );
                }
                for ( Element resultantIdentifier : resultantIdentifiers )
                {
                    patient.addElement( "resultantIdentifiers" )
                                    .add( createIdentifierCollectionElement( "resultantIdentifier", resultantIdentifier ) );
                }
            }
        }

        List<Element> excludedIdentifiers = filter.getExcludedIdentifiers();
        for ( Element excludedIdentifier : excludedIdentifiers )
        {
            patient.addElement( "requestedExcludedIdentifiers" ).add(
                            createIdentifierCollectionElement( "requestedExcludedIdentifier", excludedIdentifier ) );
        }

        return result;
    }

}
