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

/**
 * コンストラクタ引数で指定された{@link Acquirable}を順に
 * {@link Acquirable#acquire()}する{@link Acquirable}です。
 * {@link Acquirable#acquire()}による実行権の取得に失敗した場合、
 * 既に実行権を取得した{@link Acquirable}
 * を逆順に{@link Acquirable#release()}します。
 * 
 * @author nakamura
 * 
 */
public class AcquirableChain implements Acquirable {
	private Acquirable[] array;

	public AcquirableChain(final Acquirable... acquirables) {
		this.array = acquirables;
	}

	public boolean acquire() {
		int i = 0;
		try {
			while (i < array.length) {
				if (!array[i].acquire()) {
					break;
				}
				i++;
			}
		} finally {
			if (i < array.length) {
				release(i - 1);
			}
		}
		return i >= array.length;
	}

	private void release(final int length) {
		for (int i = length; i >= 0; i--) {
			array[i].release();
		}
	}

	public void release() {
		release(array.length - 1);
	}

	public Acquirable[] getArray() {
		return array;
	}
	public void setArray(final Acquirable[] array) {
		this.array = array;
	}
}
