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

import java.util.Map;

import woolpack.fn.Fn;

/**
 * 委譲先で生成したオブジェクトを{@link Map}にキャッシュして返す{@link Fn}です。
 * @author nakamura
 *
 * @param <C>
 * @param <K>
 * @param <E>
 */
public class MapCache<C, K, E extends Exception> implements Fn<C, Object, E> {
	private Fn<? super C, ? extends Map<? super K, Object>, ? extends E> mapGetter;
	private Fn<? super C, ? extends K, ? extends E> keyGetter;
	private Fn<? super C, ?, ? extends E> maker;
	
	public MapCache(
			final Fn<? super C, ? extends Map<? super K, Object>, ? extends E> mapGetter,
			final Fn<? super C, K, ? extends E> keyGetter,
			final Fn<? super C, ?, ? extends E> maker) {
		this.mapGetter = mapGetter;
		this.keyGetter = keyGetter;
		this.maker = maker;
	}

	public Object exec(final C c) throws E {
		final Map<? super K, Object> map = mapGetter.exec(c);
		final K key = keyGetter.exec(c);
		Object value = map.get(key);
		if (value == null) {
			value = maker.exec(c);
			map.put(key, value);
			return value;
		}
		return value;
	}

	public Fn<? super C, ? extends K, ? extends E> getKeyGetter() {
		return keyGetter;
	}
	public void setKeyGetter(final Fn<? super C, ? extends K, ? extends E> keyGetter) {
		this.keyGetter = keyGetter;
	}
	public Fn<? super C, ?, ? extends E> getMaker() {
		return maker;
	}
	public void setMaker(final Fn<? super C, ?, ? extends E> maker) {
		this.maker = maker;
	}
	public Fn<? super C, ? extends Map<? super K, Object>, ? extends E> getMapGetter() {
		return mapGetter;
	}
	public void setMapGetter(
			final Fn<? super C, ? extends Map<? super K, Object>, ? extends E> mapGetter) {
		this.mapGetter = mapGetter;
	}
}
