package gov.va.med.esr.messaging.parser;

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.MSH;
import gov.va.med.fw.hl7.segment.PID;
import gov.va.med.fw.hl7.segment.ZPD;
import gov.va.med.fw.util.builder.Builder;
import gov.va.med.fw.util.builder.BuilderException;

import gov.va.med.esr.common.builder.entity.EntityBuilder;
import gov.va.med.esr.common.builder.entity.PersonMetaData;
import gov.va.med.esr.common.builder.entity.metaData.PersonMetaDataFromPID;
import gov.va.med.esr.common.model.person.Person;

/**
 * Builds a Person object from a Z12/Z13 message
 * 
 * @author Rajiv Patnaik Created on Dec 19, 2005
 * @version 1.0 Copyright © 2005 VHA. All rights reserved
 */
public class Z12Z13Parser extends EntityBuilder {
   /**
    * An instance of serialVersionUID
    */
   private static final long serialVersionUID = 8415672585669755671L;

   private Builder personBuilder;

   public Person build(Object[] args) throws BuilderException {
      return this.build((Person)args[0], (Message)args[1]);
   }

   /**
    * Main method to build the BOM from the Z05 message.
    * 
    * @param input
    * @param message
    * @return Person
    * @throws BuilderException
    */
   public Person build(Person input, Message message) throws BuilderException {
      try {
         Person person = this.buildPerson(input, message);

         return person;
      }
      catch( InvalidMessageException e ) {
         throw new BuilderException(e);
      }
   }

   /**
    * @return Returns the personBuilder.
    */
   public Builder getPersonBuilder() {
      return personBuilder;
   }

   /**
    * @param personBuilder
    *           The personBuilder to set.
    */
   public void setPersonBuilder(Builder personBuilder) {
      this.personBuilder = personBuilder;
   }

   private Person buildPerson(Person input, Message message) throws BuilderException,
         InvalidMessageException {

      // Pass null for zem, zen, zel, zmh, zio
      PersonMetaData metaData = new PersonMetaDataFromPID((PID)message
            .getSegment(SegmentConstants.PID), (ZPD)message
            .getSegment(SegmentConstants.ZPD), null, null, null, (MSH)message
            .getSegment(SegmentConstants.MSH), null, null);
      metaData.setEntity(input);

      return (Person)this.personBuilder.build(metaData);
   }
}