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

/**
 * {@link Map}を使用して、キーに対する値を返す{@link Fn}です。
 * 引数に対する値が null の場合はデフォルトの処理に委譲します。
 * @author nakamura
 *
 * @param <C>
 * @param <R>
 */
public class SwitchFn<C, R> implements Fn<C, R> {
	private Map<? super C, ? extends R> map;
	private Fn<? super C, ? extends R> defaultFn;
	
	/**
	 * @param map
	 * @param defaultFn 引数に対応する値が null の場合の委譲先。
	 */
	public SwitchFn(
			final Map<? super C, ? extends R> map,
			final Fn<? super C, ? extends R> defaultFn) {
		this.map = map;
		this.defaultFn = defaultFn;
	}
	
	/**
	 * @param map
	 * @param defaultValue 引数に対応する値が null の場合の返却値。
	 */
	public SwitchFn(final Map<? super C, ? extends R> map, final R defaultValue) {
		this(map, new FixFn<C, R>(defaultValue));
	}

	/**
	 * 引数に対応する値が null の場合は null を返します。
	 * @param map
	 */
	public SwitchFn(final Map<? super C, ? extends R> map) {
		this(map, new FixFn<C, R>(null));
	}

	public R exec(final C c) {
		final R r = map.get(c);
		if (r == null) {
			return defaultFn.exec(c);
		} else {
			return r;
		}
	}

	public Fn<? super C, ? extends R> getDefaultFn() {
		return defaultFn;
	}
	public void setDefaultFn(final Fn<? super C, ? extends R> defaultFn) {
		this.defaultFn = defaultFn;
	}
	public Map<? super C, ? extends R> getMap() {
		return map;
	}
	public void setMap(final Map<? super C, ? extends R> map) {
		this.map = map;
	}
}
