/*
 * 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.dom;

/**
 * {@link Evaluable#eval(DomContext)}の返却値で委譲先を分岐する{@link DomExpression}。
 * 適用しているパターン：フィルタ。
 * @author nakamura
 *
 */
public class If implements DomExpression {
	private final Evaluable eval;
	private final DomExpression trueExpression;
	private final DomExpression falseExpression;
	
	/**
	 * コンストラクタ。評価結果が{@link Boolean}でない場合は委譲しない。
	 * @param eval 評価器。
	 * @param trueExpression 評価結果が{@link Boolean#TRUE}の場合の委譲先。
	 * @param falseExpression 評価結果が{@link Boolean#FALSE}の場合の委譲先。
	 * @throws NullPointerException 引数のいずれかが null の場合。
	 */
	public If(final Evaluable eval, final DomExpression trueExpression, final DomExpression falseExpression){
		eval.getClass();
		trueExpression.getClass();
		falseExpression.getClass();
		
		this.eval = eval;
		this.trueExpression = trueExpression;
		this.falseExpression = falseExpression;
	}

	/**
	 * コンストラクタ。評価結果が{@link Boolean#TRUE}でない場合は委譲しない。
	 * @param eval 評価器。
	 * @param trueExpression 評価結果が{@link Boolean#TRUE}の場合の委譲先。
	 * @throws NullPointerException 引数のいずれかが null の場合。
	 */
	public If(final Evaluable eval, final DomExpression trueExpression){
		this(eval, trueExpression, DomConstants.NULL);
	}

	public void interpret(final DomContext context) {
		final Object o = eval.eval(context);
		if(Boolean.TRUE.equals(o)){
			trueExpression.interpret(context);
		}else if(Boolean.FALSE.equals(o)){
			falseExpression.interpret(context);
		}
	}
}
