/********************************************************************
 * Copyright © 2004 EDS. All rights reserved
 ********************************************************************/
//Package
package gov.va.med.esr.messaging.builder.message;

//Java Classes
import java.util.Date;

//Framework Classes
import gov.va.med.fw.hl7.segment.MFE;
import gov.va.med.fw.util.builder.BuilderException;

/**
 * Class to build the MFE segment.
 * 
 * @author Alex Yoon
 * @version 1.0
 */
public class MFEBuilder extends AbstractSegmentBuilder
{
    /**
    * An instance of serialVersionUID 
    */
   private static final long serialVersionUID = 8287283686684268590L;

   public MFEBuilder()
    {
        super();
    }

    /**
     * Method to build the MFE segment.
     * 
     * @param metaData
     *            The parameter object used to build the a MFE segment.
     * @return The MFE segment.
     */
    public Object build(MFEMetaData metaData) throws BuilderException
    {
        if ((metaData == null))
        {
            throw new BuilderException(
                    "Invalid input parameter to build a segment");
        }

        MFE segment = new MFE();

        try
        {
            //Set segment attributes
            segment.setEventCode(metaData.getRecordLeveEventCode());
            
            segment.setControlID(metaData.getMfnControlID());
            
            segment.setEffectiveDate(DateFormatter.formatDate(metaData
                    .getEffectiveDate(), DateFormatter.DATETIME_ZONE_FORMAT));

            //Build effective date in legacy Fileman date format.
            String effectiveDate = buildFilemanDate(metaData
                    .getPrimaryKeyValueEffectiveDate());

            //Build Primary Key Value that is HL7 coded element.
            String primaryKeyValue = ElementFormatter.formatCodedElement(
                    effectiveDate, metaData.getPrimaryKeyValueFileName(),
                    metaData.getPrimaryKeyValueCodingSystem());

            segment.setPrimaryKeyValue(primaryKeyValue);
        } catch (Exception e)
        {
            throw new BuilderException(
                    "Failed to build MFE Segment due to an exception ", e);
        }

        return segment;
    }

    /**
     * Method that builds a date in a legacy Fileman format.
     * 
     * @param date
     *            The Date Object.
     * @return formatted date String.
     */
    private String buildFilemanDate(Date date)
    {
        String filemanDate = null;

        if (date != null)
        {
            //The first digit is the century.
            //The 1800's are 1, the 1900's are 2, and the 2000's are 3.
            //The next two digits are the year, the following 2 the month,
            //and the last 2 the date.
            //So January 16, 2003 would be 3030116.

            //TODO: write this logic
            filemanDate = "3030116";
        }

        return filemanDate;
    }
}