/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package woolpack.validator;

import java.io.IOException;
import java.util.Collection;

/**
 * 検証条件の実行結果により委譲先を分岐する{@link ValidatorExpression}。
 * @author nakamura
 *
 */
public class IfValidator extends ValidatorExpressionAdapter {
	private final ValidatorExpression ifExpression;
	private final ValidatorExpression trueExpression;
	private final ValidatorExpression falseExpression;
	
	/**
	 * コンストラクタ。
	 * @param ifExpression 検証条件。
	 * @param trueExpression 検証条件の結果が true の場合の委譲先。
	 * @param falseExpression 検証条件の結果が false の場合の委譲先。
	 * @throws NullPointerException 引数のいずれかが null の場合。
	 */
	public IfValidator(
			final ValidatorExpression ifExpression, 
			final ValidatorExpression trueExpression, 
			final ValidatorExpression falseExpression){
		ifExpression.getClass();
		trueExpression.getClass();
		falseExpression.getClass();
		
		this.ifExpression = ifExpression;
		this.trueExpression = trueExpression;
		this.falseExpression = falseExpression;
	}

	/**
	 * コンストラクタ。
	 * @param ifExpression 検証条件。
	 * 検証条件の結果が false の場合は true を返す。
	 * @param trueExpression 検証条件の結果が true の場合の委譲先。
	 * @throws NullPointerException 引数のいずれかが null の場合。
	 */
	public IfValidator(
			final ValidatorExpression ifExpression, 
			final ValidatorExpression trueExpression){
		this(ifExpression, trueExpression, ValidatorConstants.TRUE);
	}
			
	
	@Override public boolean interpret(final ValidatorContext context) {
		return ifExpression.interpret(context)?trueExpression.interpret(context):falseExpression.interpret(context);
	}

	@Override public void appendArgumentTo(final Appendable sb) throws IOException{
		ifExpression.appendTo(sb);
		sb.append(",");
		trueExpression.appendTo(sb);
		sb.append(",");
		falseExpression.appendTo(sb);
	}

	@Override public void addMessageTo(final Collection<String> messageCollection) {
		ifExpression.addMessageTo(messageCollection);
		trueExpression.addMessageTo(messageCollection);
		falseExpression.addMessageTo(messageCollection);
	}
}
