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

import woolpack.utils.CheckUtils;
import woolpack.utils.Switchable;
import woolpack.utils.concurrent.Acquirable;

/**
 * id 毎に実行権を制御する{@link DomExpression}。 適用しているパターン：Proxy、Before After、Balking。
 * 
 * @author nakamura
 * 
 */
public class DoAcquire implements DomExpression {
	private final Switchable<String, Acquirable> map;

	private final DomExpression trueExpression;

	private final DomExpression falseExpression;

	/**
	 * コンストラクタ。
	 * 
	 * @param map
	 *            id と{@link Acquirable}の{@link Switchable}。
	 *            本クラスはこの引数の{@link Acquirable}の状態を変化させる。
	 * @param trueExpression
	 *            実行権の取得に成功したか id に対する{@link Acquirable}が設定されていない場合の委譲先。
	 * @param falseExpression
	 *            実行権の取得に失敗した場合の委譲先。
	 * @throws NullPointerException
	 *             引数のいずれかが null の場合。
	 */
	public DoAcquire(final Switchable<String, Acquirable> map,
			final DomExpression trueExpression,
			final DomExpression falseExpression) {
		CheckUtils.checkNotNull(map);
		CheckUtils.checkNotNull(trueExpression);
		CheckUtils.checkNotNull(falseExpression);

		this.map = map;
		this.trueExpression = trueExpression;
		this.falseExpression = falseExpression;
	}

	public void interpret(final DomContext context) {
		final Acquirable acquirable = map.get(context.getId());
		if (acquirable != null) {
			if (acquirable.acquire()) {
				try {
					trueExpression.interpret(context);
				} finally {
					acquirable.release();
				}
			} else {
				falseExpression.interpret(context);
			}
		} else {
			trueExpression.interpret(context);
		}
	}
}
