/********************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ********************************************************************/
package gov.va.med.esr.messaging.service.inbound;

// Java Classes

// Library Classes

// Framework Classes
import gov.va.med.esr.common.builder.datatype.metadata.CX;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.service.PersonIdentityTraits;
import gov.va.med.fw.hl7.InvalidMessageException;
import gov.va.med.fw.hl7.Message;
import gov.va.med.fw.hl7.constants.SegmentConstants;
import gov.va.med.fw.hl7.segment.PID;
import gov.va.med.fw.service.ServiceException;

// Messaging Classes

/**
 * @author Martin Francisco
 */
public class PersonFinderFromVista extends AbstractPersonFinderFromVista {
	/*
	 * (non-Javadoc)
	 * 
	 * @see gov.va.med.esr.messaging.service.inbound.PersonFinder#find(gov.va.med.fw.hl7.Message)
	 */
	public Person find(Message message) throws ServiceException {
		try {
			String dfn = getDfn((PID) message.getSegment(SegmentConstants.PID));
			String stationNumber = getSendingFacilityStationNumber(message);

			//CCR 11758: use the composite call to see if 200ESR Correlation exists
			PersonIdentityTraits identityTraits = this.getPsDelegateService().getIdentityTraitsWithCompositeCall(dfn,
	    			stationNumber);
			Person onFile = this.getPersonService().find(identityTraits);
			
	        //CCR 11403: for Vista inbound messages, check enrollment records, add 200ESRCorreltion if necessary
            //CCR 11758
			
			if ("N".equalsIgnoreCase(identityTraits.has200ESRCorrelation())) {
				/*** Do this later time when we have address populated in incoming person
				this.getPersonService().addESRCorrelation(onFile);
				***/
				onFile.setEsrCorrelationAdded(false); //CCR 12176 - incoming message with new person that ESR correlation is just added				
			} else {
				onFile.setEsrCorrelationAdded(true);
			}
			
	        return onFile;
		} catch (InvalidMessageException e) {
			// ASSERT: Should not happen if the message is already parsed.
			throw new RuntimeException(
					"Failed to obtain the dfn from the PID segment", e);
		}
	}

	
	/**
	 * Get DFN from PID-3 segment. PID-3 is a CX datatype and DFN data has the
	 * "PI" Identifier type.
	 * 
	 * @param pid
	 * @return dfn value as String
	 */
	private String getDfn(PID pid) {
		CX[] cxs = CX.create(pid.getPatientIdentifierList(), pid
				.getRepeatDelimiter(), pid.getComponentDelimiter(), pid
				.getSubComponentDelimiter());

		String dfn = CX.getIdentifierByIdentifierType(cxs,
				SegmentConstants.IDENTIFIER_TYPE_PI);

		return dfn;
	}

}