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

import woolpack.fn.Fn;

/**
 * 委譲先を順次呼び出して集計する{@link Fn}です。
 * @author nakamura
 *
 * @param <C>
 * @param <E>
 */
public class BoolSeq<C, E extends Exception> implements Fn<C, Boolean, E> {
	private Fn<Object, ? extends BooleanState, ? extends RuntimeException> factory;
	private Iterable<? extends Fn<? super C, Boolean, ? extends E>> iterable;
	
	public BoolSeq(
			final Fn<Object, ? extends BooleanState, ? extends RuntimeException> factory,
			final Iterable<? extends Fn<? super C, Boolean, ? extends E>> iterable) {
		this.factory = factory;
		this.iterable = iterable;
	}

	public Boolean exec(final C c) throws E {
		final BooleanState state = factory.exec(null);
		for (final Fn<? super C, Boolean, ? extends E> e : iterable) {
			state.in(e.exec(c));
			if (state.isStopped()) {
				break;
			}
		}
		return state.isCurrent();
	}
	
	public Iterable<? extends Fn<? super C, Boolean, ? extends E>> getIterable() {
		return iterable;
	}
	public void setIterable(final Iterable<? extends Fn<? super C, Boolean, ? extends E>> iterable) {
		this.iterable = iterable;
	}
	public Fn<Object, ? extends BooleanState, ? extends RuntimeException> getFactory() {
		return factory;
	}
	public void setFactory(final Fn<Object, ? extends BooleanState, ? extends RuntimeException> factory) {
		this.factory = factory;
	}
}
