/********************************************************************
 Copyright © 2004 VHA. All rights reserved
 ********************************************************************/
package gov.va.med.fw.util.builder.decorator;

import gov.va.med.fw.util.builder.Builder;
import gov.va.med.fw.util.builder.BuilderException;
import gov.va.med.fw.util.builder.Validator;
import gov.va.med.fw.util.builder.ValidatorException;

/**
 * Builder decorator that validates the results of the builder.
 * 
 * @author Martin Francisco
 */
public class PostValidatingBuilder
    extends AbstractBuilderDecorator
{
    /**
	 * An instance of serialVersionUID
	 */
	private static final long serialVersionUID = -3727312062752313154L;
	/**
     * The post-validator.
     */
    private Validator postValidator;

    /**
     * Factory method to create a pre-process builder.
     * 
     * @param builder
     *        The builder being decorated.
     * @param postValidator
     *        The post-validator.
     * @return The post-validating builder.
     * @throws IllegalArgumentException
     *         Thrown if the builder is null.
     * @throws IllegalArgumentException
     *         Thrown if the postValidator is null.
     */
    public static Builder decorate(Builder builder, Validator postValidator)
    {
        return new PostValidatingBuilder(builder, postValidator);
    }

    /**
     * Constructs the decorator.
     * 
     * @param builder
     *        The builder being decorated.
     * @param postValidator
     *        The post-validator.
     * @throws IllegalArgumentException
     *         Thrown if the builder is null.
     * @throws IllegalArgumentException
     *         Thrown if the postValidator is null.
     */
    protected PostValidatingBuilder(Builder builder, Validator postValidator)
    {
        super(builder);

        if(postValidator == null)
        {
            throw new IllegalArgumentException("postValidator cannot be null");
        }
        else
        {
            this.postValidator = postValidator;
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see gov.va.med.fw.util.builder.AbstractBuilder#build(java.lang.Object)
     */
    public Object build(Object input) throws BuilderException
    {
        try
        {
            Object result = super.getBuilder().build(input);

            if(result != null)
            {
                this.postValidator.validate(result);
            }

            return result;
        }
        catch(ValidatorException e)
        {
            throw new BuilderException(e.getMessage(), e);
        }
    }
}