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

import java.util.Collection;


/**
 * 通過情報を{@link Collection}に記録するテスト用の{@link Fn}です。
 * @author nakamura
 *
 * @param <C>
 * @param <R>
 */
public class RecodeFn<C, R> implements Fn<C, R> {
	private Fn<? super C, ? extends R> fn;
	private String name;
	private Collection<String> nameList;
	private Collection<? super C> contextList;
	private Collection<? super R> returnList;
	
	/**
	 * @param fn 委譲先。null の場合は委譲しません。
	 * @param name nameListに追加する名前。
	 * @param nameList name を追加する対象。null の場合は追加しません。
	 * @param contextList コンテキスト役を追加する対象。null の場合は追加しません。
	 * @param returnList 委譲先を追加する対象。null の場合は追加しません。
	 */
	public RecodeFn(
			final Fn<? super C, ? extends R> fn,
			final String name,
			final Collection<String> nameList,
			final Collection<? super C> contextList,
			final Collection<? super R> returnList) {
		this.fn = fn;
		this.name = name;
		this.nameList = nameList;
		this.contextList = contextList;
		this.returnList = returnList;
	}
	
	public RecodeFn(
			final Fn<? super C, ? extends R> fn,
			final String name,
			final Collection<String> nameList) {
		this(fn, name, nameList, null, null);
	}
	
	public RecodeFn(
			final Fn<? super C, ? extends R> fn,
			final Collection<? super C> contextList,
			final Collection<? super R> returnList) {
		this(fn, null, null, contextList, returnList);
	}

	public R exec(final C c) {
		if (nameList != null) {
			nameList.add(name);
		}
		if (contextList != null) {
			contextList.add(c);
		}
		R r = null;
		if (fn != null) {
			r = fn.exec(c);
		}
		if (returnList != null) {
			returnList.add(r);
		}
		return r;
	}

	public Collection<? super C> getContextList() {
		return contextList;
	}
	public void setContextList(final Collection<? super C> contextList) {
		this.contextList = contextList;
	}
	public String getName() {
		return name;
	}
	public void setName(final String name) {
		this.name = name;
	}
	public Collection<String> getNameList() {
		return nameList;
	}
	public void setNameList(final Collection<String> nameList) {
		this.nameList = nameList;
	}
	public Fn<? super C, ? extends R> getFn() {
		return fn;
	}
	public void setFn(final Fn<? super C, ? extends R> fn) {
		this.fn = fn;
	}
	public Collection<? super R> getReturnList() {
		return returnList;
	}
	public void setReturnList(final Collection<? super R> returnList) {
		this.returnList = returnList;
	}
}
