/**
 * 
 */


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;


/**
 * @author vhaislegberb
 * 
 */
public class CustomPipeParser
    extends
        PipeParser
{
    public CustomPipeParser( )
    {
        this( new CustomCdsModelClassFactory() );
    }

    
    public CustomPipeParser( ModelClassFactory modelClassFactory )
    {
    	super( new CdsHapiContext(modelClassFactory));
    }
    
    @Override
    protected String doEncode( Message source )
        throws HL7Exception
    {
        try
        {
            // 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: BHS-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 );
        }
        catch ( HL7Exception e )
        {
            return super.doEncode( source );
        }
    }
      
}
