package gov.va.med.esr.messaging.builder.message;

import gov.va.med.esr.common.model.lookup.County;
import gov.va.med.esr.common.model.party.Address;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.service.trigger.PersonTriggerEvent;
import gov.va.med.fw.hl7.builder.HL7MetaData;
import gov.va.med.fw.hl7.segment.ZTA;
import gov.va.med.fw.service.ServiceException;
import gov.va.med.fw.util.StringUtils;
import gov.va.med.fw.util.builder.BuilderException;

public class ZTAZ05Builder extends AbstractZTABuilder {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7152723253656357808L;
	

	
	/**
     * Method to build the ZTA segment.
     * 
     * @param metaData
     *            The parameter object used to build the a ZPD segment.
     * @return The ZTA segment.
     */
    public Object build(HL7MetaData metaData, PersonTriggerEvent triggerEvent)
            throws BuilderException
    {
        if ((metaData == null) || (metaData.getEntity() == null)
                || !(metaData.getEntity() instanceof Person)
                || triggerEvent == null)
        {
            throw new BuilderException(
                    "Invalid input parameter to build a segment");
        }

        ZTA segment = new ZTA();
        segment.setSetID("1");

        Person person = (Person) metaData.getEntity();

        try
        {
        	// if temp address is present then set it here.
        	
        	Address  tempAddress = person.getTemporaryCorrespondenceAddress();
        	
        	if ( tempAddress != null )
        	{
        		//	Sequence 2 
        		segment.setTemporaryAddressIndicator(buildBooleanForVA001(new Boolean(tempAddress.isActive())));
        		
        		//	sequence 3
        		segment.setTemporaryAddressStartDate(DateFormatter.formatDate(tempAddress.getStartDate()));
        		
        		//	sequence 4
        		segment.setTemporaryAddressEndDate(DateFormatter.formatDate(tempAddress.getEndDate()));
        		
        		//	sequence 5
        		segment.setTemporaryAddress(addressFormatter.formatAddress(tempAddress));
        		
        		// sequence 6.
                County county = null;
                try
                {
                    county = getLookupService().getCountyByAddress(tempAddress);                
                } catch (ServiceException e)
                {
                    //Ignore the exception, invalid zip code or it is a postal code
                }
                segment.setTemporaryAddressCounty(county == null ? StringUtils.EMPTY : county.getCountyNumber());
                
                // sequence 7
                segment.setTemporaryAddressPhoneNumber(tempAddress.getPhoneNumber());
                
                // sequence 8
               //ESR 3.5_CodeCR11154 -_ST_- ZTA not correctly capturing date/timestamp in ORU-Z05
                if(tempAddress.getChangeDate() !=null){
                	segment.setTemporaryAddressLastUpdatedDate(DateFormatter.formatDateTime(tempAddress.getChangeDate(),DateFormatter.DATETIME_ZONE_FORMAT));
                }
                
                // sequence 9
                // CCR 10248: Z05 messages are failing with null pointer as the changeSite is null in temporary address
                String siteOfChangeNumber = null;
                try {
                	if (tempAddress.getChangeSite() != null) {
                		siteOfChangeNumber = tempAddress.getChangeSite().getStationNumber();
                		if( logger.isDebugEnabled() ) {
                            logger.debug("Z05 change site not null=" +  siteOfChangeNumber);
                        }
                	} else {
                		// substitute it with sending facillity if ZTA-9 is null
                		siteOfChangeNumber = person.getSendingFacility();
                		if( logger.isDebugEnabled() ) {
                            logger.debug("Z05 change site null. Sustitute sendingfacility =" +  person.getSendingFacility());
                        }
                	}
                } catch (Exception ne) {
                	throw new BuilderException(
                    "Failed to build ZTA Segment-9 for Z05 due to an exception " + ne);
                }
                segment.setTemporaryAddressChangeSite(siteOfChangeNumber); 
	        }
	            
        } catch (Exception e)
        {
            throw new BuilderException(
                    "Failed to build ZTA Segment for Z05 due to an exception ", e);
        }

        return segment;
    }


}
