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

import woolpack.fn.Fn;

public class RetryFn<C, R, E extends Exception> implements Fn<C, R, E> {
	private Fn<? super C, ? extends R, ? extends Exception> fn;
	private int count;
	private Fn<? super Exception, ?, ? extends E> errorFn;
	private Fn<? super Exception, ? extends R, ? extends E> finalFn;
	
	public RetryFn(
			final Fn<? super C, ? extends R, ? extends Exception> fn,
			final int count,
			final Fn<? super Exception, ?, ? extends E> errorFn,
			final Fn<? super Exception, ? extends R, ? extends E> finalFn) {
		this.fn = fn;
		this.count = count;
		this.errorFn = errorFn;
		this.finalFn = finalFn;
	}

	public R exec(final C c) throws E {
		Exception t = null;
		for (int i = 0; i < count; i++) {
			try {
				return fn.exec(c);
			} catch (final Exception e) {
				t = e;
				errorFn.exec(t);
			}
		}
		return finalFn.exec(t);
	}

	public int getCount() {
		return count;
	}
	public void setCount(final int count) {
		this.count = count;
	}
	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 Fn<? super C, ? extends R, ? extends Exception> getFn() {
		return fn;
	}
	public void setFn(final Fn<? super C, ? extends R, ? extends Exception> fn) {
		this.fn = fn;
	}
}
