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

import woolpack.fn.Fn;

/**
 * 取得した{@link Acquirable}で実行権を制御する{@link Fn}です。
 * 
 * @author nakamura
 *
 * @param <C>
 * @param <R>
 * @param <E>
 */
public class AcquireFn<C, R, E extends Exception> implements Fn<C, R, E> {
	private Fn<? super C, ? extends Acquirable<? extends E>, ? extends E> acquireGetter;
	private Fn<? super C, ? extends R, ? extends E> trueFn;
	private Fn<? super C, ? extends R, ? extends E> falseFn;

	/**
	 * @param acquireGetter コンテキストから{@link Acquirable}を抽出する委譲先。
	 * @param trueFn 実行権の取得に成功したか{@link Acquirable}が抽出できなかった場合の委譲先。
	 * @param falseFn 実行権の取得に失敗した場合の委譲先。
	 */
	public AcquireFn(
			final Fn<? super C, ? extends Acquirable<? extends E>, ? extends E> acquireGetter,
			final Fn<? super C, ? extends R, ? extends E> trueFn,
			final Fn<? super C, ? extends R, ? extends E> falseFn) {
		this.acquireGetter = acquireGetter;
		this.trueFn = trueFn;
		this.falseFn = falseFn;
	}

	public R exec(final C c) throws E {
		final Acquirable<? extends E> acquirable = acquireGetter.exec(c);
		if (acquirable != null) {
			if (acquirable.acquire()) {
				try {
					return trueFn.exec(c);
				} finally {
					acquirable.release();
				}
			} else {
				return falseFn.exec(c);
			}
		} else {
			return trueFn.exec(c);
		}
	}

	public Fn<? super C, ? extends R, ? extends E> getFalseFn() {
		return falseFn;
	}
	public void setFalseFn(final Fn<? super C, ? extends R, ? extends E> falseFn) {
		this.falseFn = falseFn;
	}
	public Fn<? super C, ? extends Acquirable<? extends E>, ? extends E> getAcquireGetter() {
		return acquireGetter;
	}
	public void setAcquireGetter(final Fn<? super C, ? extends Acquirable<? extends E>, ? extends E> acquireGetter) {
		this.acquireGetter = acquireGetter;
	}
	public Fn<? super C, ? extends R, ? extends E> getTrueFn() {
		return trueFn;
	}
	public void setTrueFn(final Fn<? super C, ? extends R, ? extends E> trueFn) {
		this.trueFn = trueFn;
	}
}
