/********************************************************************
 * Copyright © 2005 VHA. All rights reserved
 ********************************************************************/

package gov.va.med.fw.hl7;

import java.util.List;

import gov.va.med.fw.hl7.segment.MSA;
import gov.va.med.fw.util.StringUtils;

/**
 * Initial javadoc for class AckMessage. TODO - Add content here
 * 
 * Created Nov 11, 2005 2:25:40 PM
 * 
 * @author DNS   BOHMEG
 */
public class AckMessage extends HL7Message {
	
	/**
	 * An instance of serialVersionUID
	 */
	private static final long serialVersionUID = 2053766024217320499L;

	/**
	 * A default constructor
	 */
	public AckMessage(Message message) {
		super(message);
	}

	/**
	 * A default constructor
	 * 
	 * @param data
	 * @throws InvalidMessageException
	 */
	public AckMessage(String data) throws InvalidMessageException {
		super(data);
	}

	/**
	 * A default constructor
	 * 
	 * @param data
	 * @param type
	 * @throws InvalidMessageException
	 */
	public AckMessage(String data, String type) throws InvalidMessageException {
		super(data, type);
	}

	/**
	 * A default constructor
	 * 
	 * @param segments
	 * @throws InvalidMessageException
	 */
	public AckMessage(List segments) throws InvalidMessageException {
		super(segments);
	}

	/**
	 * A default constructor
	 * 
	 * @param segments
	 * @param type
	 * @throws InvalidMessageException
	 */
	public AckMessage(List segments, String type)
			throws InvalidMessageException {
		super(segments, type);
	}

	public boolean isBatch() throws InvalidMessageException {
		return getBHSSegment() != null;
	}
	
	public boolean isQueryResponse() throws InvalidMessageException {
		return (getMSHSegment().getMessageType().indexOf("ORF") > -1) ? true : false;
	}
	
	public BatchMessage getAsBatch() throws InvalidMessageException {	
		String messageType = getMessageType();
		// for a query response ACK, the message type of the batch should not be ACK
		if(isQueryResponse())
			messageType = StringUtils.replace(getMSHSegment().getMessageType(), "~", "");
		return new BatchMessage(getSegments(), messageType);
	}
	
	/** This could return a Batch Control Number (in case of an ACK to an entire batch) or a
	 * single Message Control Number (in case of an ACK to a single message).
	 * @return
	 * @throws InvalidMessageException
	 */
	public String getReferencedControlNumber() throws InvalidMessageException {
		MSA msa = getMSASegment();
		if(msa == null)
			throw new InvalidMessageException("An AckMessage must have an MSA segment");
		return msa.getMessageControlID();
	}
}
