package gov.va.med.esr.common.builder.entity;

import gov.va.med.esr.common.model.lookup.EmailSourceOfChange;
import gov.va.med.esr.common.model.lookup.EmailType;
import gov.va.med.esr.common.model.party.Email;
import gov.va.med.fw.util.builder.Builder;
import gov.va.med.fw.util.builder.BuilderException;

/**
 * Builds a Email Address from Email metadata.
 *  
 * @author Rajiv Patnaik Created on Jan 27, 2006
 * @version 1.0
 * 
 * Copyright © 2006 VHA. All rights reserved
 */
public class EmailBuilder extends EntityBuilder
{
	private static final long serialVersionUID = -4764005178073222016L;

    private Builder changeSourceBuilder;
    private Builder typeBuilder;

    public EmailBuilder()
    {
        super();
    }

    public Builder getTypeBuilder()
    {
        return this.typeBuilder;
    }

    public void setTypeBuilder(Builder typeBuilder)
    {
        this.typeBuilder = typeBuilder;
    }

    
    /**
     * @return Returns the changeSourceBuilder.
     */
    public Builder getChangeSourceBuilder()
    {
        return changeSourceBuilder;
    }
    /**
     * @param changeSourceBuilder The changeSourceBuilder to set.
     */
    public void setChangeSourceBuilder(Builder changeSourceBuilder)
    {
        this.changeSourceBuilder = changeSourceBuilder;
    }
    
    public Email build(EmailMetaData metaData) throws BuilderException
    {
        Email input = metaData.getEntity();
        Email output = (input == null) ? new Email() : input;
        this.transfer(output, metaData);

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

    private EmailType buildType(EmailType input, String code)
            throws BuilderException
    {
        return (EmailType) super.build(this.typeBuilder, input, code);
    }

    private boolean shouldKeep(Email obj)
    {
        return (obj.getAddress() != null);
    }

    private void transfer(Email input, EmailMetaData metaData)
            throws BuilderException
    {
        input.setAddress(super.build(input.getAddress(), metaData
                .getEmailAddress()));
        input.setChangeDate(super.build(input.getChangeDate(), metaData
                .getChangeDate()));
        input.setSiteOfChange(super.build(input.getSiteOfChange(), metaData
                .getChangeSite()));
        input.setSourceOfChange(
                (EmailSourceOfChange) super.build(this.changeSourceBuilder,
                        input.getSourceOfChange(), metaData.getChangeSource()));     
        
        //FIXME Default input type as Personal. Currently incoming messages do not have any 
        //email type and their is only one email for veteran. However UI needs a email
        //type to display. This is a temporary fix till the email type is removed from the
        //database and the UI is changed accordingly
        input.setType(this.buildType(input.getType(), EmailType.CODE_PRIVATE.getName()));
    }
}

