/********************************************************************
 * Copyright © 2004 EDS. All rights reserved
 ********************************************************************/
package gov.va.med.esr.common.builder.entity;

// Java Classes

// Library Classes

// Framework Classes
import gov.va.med.fw.util.builder.Builder;
import gov.va.med.fw.util.builder.BuilderException;

// Common Classes
import gov.va.med.esr.common.model.insurance.InsuranceSubscriber;
import gov.va.med.esr.common.model.lookup.InsuredRelationship;

// Messaging Classes

/**
 * Builds a rated disability from a message and a person if elements in the IN1
 * segments are present
 * 
 * @author Carlos Ruiz
 * @version 1.0
 */
public class InsuranceSubscriberBuilder
    extends EntityBuilder
{
    /**
	 * An instance of serialVersionUID
	 */
	private static final long serialVersionUID = 2010629225153484054L;
	private Builder relationshipBuilder;

    /**
     * Default constructor.
     */
    public InsuranceSubscriberBuilder()
    {
        super();
    }

    public Builder getRelationshipBuilder()
    {
        return this.relationshipBuilder;
    }

    public void setRelationshipBuilder(Builder relationshipBuilder)
    {
        this.relationshipBuilder = relationshipBuilder;
    }

    public InsuranceSubscriber build(InsuranceSubscriberMetaData metaData)
        throws BuilderException
    {
        InsuranceSubscriber input = metaData.getEntity();
        InsuranceSubscriber output = (input == null) ? new InsuranceSubscriber()
            : input;

        this.transfer(output, metaData);

        return this.shouldKeep(output) ? output : null;
    }

    private String buildName(String input, NameMetaData metaData)
        throws BuilderException
    {
        //NOTE: Message does not conform to HL7 Spec
        //Object[] args = new Object[] { input, pn };

        //return (Name)this.nameBuilder.build(args);

        if(metaData == null)
        {
            return input;
        }
        else
        {
            return super.build(input, metaData.getFamilyName());
        }
    }

    private InsuredRelationship buildRelationship(
        InsuredRelationship input,
        String code) throws BuilderException
    {
        return super.shouldDelete(code) ? null : (InsuredRelationship)super
            .build(this.relationshipBuilder, input, code);
    }

    private boolean shouldKeep(InsuranceSubscriber obj)
    {
        return ((obj.getName() != null) || (obj.getRelationship() != null));
    }

    private void transfer(
        InsuranceSubscriber input,
        InsuranceSubscriberMetaData metaData) throws BuilderException
    {
        input.setName(this.buildName(input.getName(), metaData.getName()));
        input.setRelationship(this
            .buildRelationship(input.getRelationship(), metaData
                .getRelationship()));
    }
}