

package gov.va.med.cds.hapi.extension;


import ca.uhn.hl7v2.ErrorCode;
import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.Group;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.Segment;
import ca.uhn.hl7v2.parser.EncodingCharacters;
import ca.uhn.hl7v2.parser.ModelClassFactory;
import ca.uhn.hl7v2.parser.PipeParser;
import ca.uhn.hl7v2.util.Terser;


public class CustomBatchMessageParser
    extends
        PipeParser
{

    public CustomBatchMessageParser( )
    {
        this( new CustomCdsModelClassFactory() );
    }


    public CustomBatchMessageParser( ModelClassFactory modelClassFactory )
    {
    	super( new CdsHapiContext(modelClassFactory));
    }


    /**
     * Formats a Message object into an HL7 message string using this parser's default encoding ("VB").
     * 
     * @throws HL7Exception if the data fields in the message do not permit encoding (e.g. required fields are null)
     */
    protected String doEncode( Message source )
        throws HL7Exception
    {
        // get encoding characters ...
        Segment bhs = ( Segment )source.get( "BHS" );
        String fieldSepString = Terser.get( bhs, 1, 0, 1, 1 );

        if ( fieldSepString == null )
            throw new HL7Exception( "Can't encode message: MSH-1 (field separator) is missing" );

        char fieldSep = '|';
        if ( fieldSepString != null && fieldSepString.length() > 0 )
            fieldSep = fieldSepString.charAt( 0 );

        String encCharString = Terser.get( bhs, 2, 0, 1, 1 );

        if ( encCharString == null )
            throw new HL7Exception( "Can't encode message: MSH-2 (encoding characters) is missing" );

        if ( encCharString.length() != 4 )
            throw new HL7Exception( "Encoding characters '" + encCharString + "' invalid -- must be 4 characters", ErrorCode.DATA_TYPE_ERROR );
        EncodingCharacters en = new EncodingCharacters( fieldSep, encCharString );

        // pass down to group encoding method which will operate recursively on
        // children ...
        return encode( ( Group )source, en );
    }

}
