/********************************************************************
 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 input of the builder.
 * 
 * @author Martin Francisco
 */
public class InputValidatedBuilder extends AbstractBuilderDecorator {
	/**
	 * An instance of serialVersionUID
	 */
	private static final long serialVersionUID = -8191057741035141705L;
	/**
	 * The input validator.
	 */
	private Validator inputValidator;

	/**
	 * Factory method to create a input validated builder.
	 * 
	 * @param builder
	 *            The builder being decorated.
	 * @param inputValidator
	 *            The input validator.
	 * @return The input validated builder.
	 * @throws IllegalArgumentException
	 *             Thrown if the builder is null.
	 * @throws IllegalArgumentException
	 *             Thrown if the postValidator is null.
	 */
	public static Builder decorate(Builder builder, Validator inputValidator) {
		return new InputValidatedBuilder(builder, inputValidator);
	}

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

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

	/*
	 * (non-Javadoc)
	 * 
	 * @see gov.va.med.fw.util.builder.AbstractBuilder#build(java.lang.Object)
	 */
	public Object build(Object input) throws BuilderException {
		try {
			if (input != null) {
				this.inputValidator.validate(input);
			}

			return super.getBuilder().build(input);
		} catch (ValidatorException e) {
			throw new BuilderException(e.getMessage(), e);
		}
	}
}