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

/**
 * 実行権制御のユーティリティです。
 * 型推論で表記を簡略するためのスタティックメソッドを含みます。
 * 
 * @author nakamura
 * 
 */
public final class AcquirableUtils {

	/**
	 * 無制限に実行権を与える{@link Acquirable}です。
	 */
	public static final Acquirable ANY = new Acquirable() {
		public boolean acquire() {
			return true;
		}
		public void release() {
			// nothing to do.
		}
	};

	/**
	 * 常に実行権を与えない{@link Acquirable}です。
	 */
	public static final Acquirable NONE = new Acquirable() {
		public boolean acquire() {
			return false;
		}
		public void release() {
			// nothing to do.
		}
	};

	/**
	 * 常に実行権を与えず、実行したスレッドに対し{@link Thread#interrupt()}を実行する{@link Acquirable}です。
	 */
	public static final Acquirable INTERRUPT = new Acquirable() {
		public boolean acquire() {
			Thread.currentThread().interrupt();
			return false;
		}
		public void release() {
			// nothing to do.
		}
	};

	/**
	 * 常に実行権を与えず、
	 * 実行したスレッドに対し{@link Thread#interrupt()}を実行し、
	 * {@link InterruptedException}を原因として持つ
	 * {@link IllegalStateException}を投げる{@link Acquirable}です。
	 */
	public static final Acquirable INTERRUPTED_EXCEPTION = new Acquirable() {
		public boolean acquire() {
			Thread.currentThread().interrupt();
			throw new IllegalStateException(new InterruptedException());
		}

		public void release() {
			// nothing to do.
		}
	};

	private AcquirableUtils() {
	}
	
	public static <C, R> AcquireFn<C, R> acquire(
			final Fn<? super C, ? extends Acquirable> acquireGetter,
			final Fn<? super C, ? extends R> trueFn,
			final Fn<? super C, ? extends R> falseFn) {
		return new AcquireFn<C, R>(acquireGetter, trueFn, falseFn);
	}
}
