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

/**
 * Java の try-catch-finallyのそれぞれのブロックで委譲する{@link Fn}です。
 * @author nakamura
 * 
 * @param <C>
 * @param <R>
 */
public class TryFn<C, R> extends Delegator<C, R> {
	private Fn<? super Throwable, ? extends R> reportFn;
	private Fn<? super C, ? extends R> finallyFn;

	/**
	 * @param fn try ブロックにおける委譲先。
	 * @param reportFn catch ブロックにおける委譲先。
	 * @param finallyFn finally ブロックにおける委譲先。
	 */
	public TryFn(
			final Fn<? super C, ? extends R> fn,
			final Fn<? super Throwable, ? extends R> reportFn,
			final Fn<? super C, ? extends R> finallyFn) {
		super(fn);
		this.reportFn = reportFn;
		this.finallyFn = finallyFn;
	}

	@Override
	public R exec(final C c) {
		try {
			return super.exec(c);
		} catch (final RuntimeException t) {
			return reportFn.exec(t);
		} finally {
			finallyFn.exec(c);
		}
	}

	public Fn<? super Throwable, ? extends R> getReportFn() {
		return reportFn;
	}
	public void setReportFn(final Fn<? super Throwable, ? extends R> reportFn) {
		this.reportFn = reportFn;
	}
	public Fn<? super C, ? extends R> getFinallyFn() {
		return finallyFn;
	}
	public void setFinallyFn(final Fn<? super C, ? extends R> finallyFn) {
		this.finallyFn = finallyFn;
	}
}
