/*
 * 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>
 */
public class AcquireFn<C, R> implements Fn<C, R> {
	private Fn<? super C, ? extends Acquirable> acquireGetter;
	private Fn<? super C, ? extends R> trueFn;
	private Fn<? super C, ? extends R> falseFn;

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

	public R exec(final C c) {
		final Acquirable 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> getFalseFn() {
		return falseFn;
	}
	public void setFalseFn(final Fn<? super C, ? extends R> falseFn) {
		this.falseFn = falseFn;
	}
	public Fn<? super C, ? extends Acquirable> getAcquireGetter() {
		return acquireGetter;
	}
	public void setAcquireGetter(final Fn<? super C, ? extends Acquirable> acquireGetter) {
		this.acquireGetter = acquireGetter;
	}
	public Fn<? super C, ? extends R> getTrueFn() {
		return trueFn;
	}
	public void setTrueFn(final Fn<? super C, ? extends R> trueFn) {
		this.trueFn = trueFn;
	}
}
