package gov.va.med.esr.messaging.service.inbound;

import gov.va.med.esr.common.model.ee.IncomingMessageInfo;
import gov.va.med.esr.common.model.lookup.VAFacility;
import gov.va.med.esr.common.model.messaging.MessageLogEntry;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.fw.hl7.Message;
import gov.va.med.fw.hl7.segment.QRD;

/**
 * Processes the inbound QRYZ10 and QRYZ10 message from Vista.
 * 
 * @author DNS   CHENJ2
 * @version 1.0
 */
public abstract class AbstractQRYInboundProcessService extends
		AbstractInboundProcessService {

	/*
	 * (non-Javadoc)
	 * @see gov.va.med.esr.messaging.service.inbound.AbstractInboundProcessService#doProcessMessage(gov.va.med.esr.common.model.person.Person, gov.va.med.fw.hl7.Message, java.lang.String)
	 */
	protected MessageLogEntry doProcessMessage(Person person, Message message,
			String formattedBody) throws InboundProcessException {
        try
        {
            VAFacility sendingFacility = getLookupService()
                    .getVaFacilityByStationNumber(message.getSendingFacility());
            
            QRD qrd = (QRD)message.getSegment("QRD");
            
            // Code_CR6852: for ORFZ10 and ORFZ11, take the station+dfn directly
        	// from the inbound message (as SiteIdentity).
			String dfn = qrd.getQueryID();
            
             //Invoke Rules
            IncomingMessageInfo messageInfo = new IncomingMessageInfo();
            
            messageInfo.setQueryDateTime(super.buildDate(qrd.getQueryDate()));
            messageInfo.setReferenceMessageId(message.getMessageID());
            messageInfo.setSendingFacility(sendingFacility);
            messageInfo.setDfn(dfn);
            
            doProcessQRYMessage(person, message, messageInfo);
            
            return super.createMessageLog(message, formattedBody, person);
            
        } catch (Exception e)
        {
            throw super.createInboundProcessException(message, formattedBody,
                    person, e.getMessage(), e);
        }
	}

	abstract protected void doProcessQRYMessage(Person person, Message message, IncomingMessageInfo messageInfo)
		throws Exception;
}
