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

import woolpack.fn.Fn;

/**
 * 成功するまで順に委譲する{@link Fn}です。
 * @author nakamura
 *
 * @param <C>
 * @param <R>
 * @param <E>
 */
public class TrysFn<C, R, E extends Exception> implements Fn<C, R, E> {
	private Iterable<? extends Fn<? super C, ? extends R, ? extends Exception>> iterable;
	private Fn<? super Exception, ?, ? extends E> errorFn;
	private Fn<? super Exception, ? extends R, ? extends E> finalFn;
	
	public TrysFn(
			final Iterable<? extends Fn<? super C, ? extends R, ? extends Exception>> iterable,
			final Fn<? super Exception, ?, ? extends E> errorFn,
			final Fn<? super Exception, ? extends R, ? extends E> finalFn) {
		this.iterable = iterable;
		this.errorFn = errorFn;
		this.finalFn = finalFn;
	}

	public R exec(final C c) throws E {
		Exception t = null;
		for (final Fn<? super C, ? extends R, ? extends Exception> fn : iterable) {
			try {
				return fn.exec(c);
			} catch (final Exception e) {
				t = e;
				errorFn.exec(t);
			}
		}
		return finalFn.exec(t);
	}

	public Fn<? super Exception, ?, ? extends E> getErrorFn() {
		return errorFn;
	}
	public void setErrorFn(final Fn<? super Exception, ?, ? extends E> errorFn) {
		this.errorFn = errorFn;
	}
	public Fn<? super Exception, ? extends R, ? extends E> getFinalFn() {
		return finalFn;
	}
	public void setFinalFn(final Fn<? super Exception, ? extends R, ? extends E> finalFn) {
		this.finalFn = finalFn;
	}
	public Iterable<? extends Fn<? super C, ? extends R, ? extends Exception>> getIterable() {
		return iterable;
	}
	public void setIterable(
			final Iterable<? extends Fn<? super C, ? extends R, ? extends Exception>> iterable) {
		this.iterable = iterable;
	}
}
