/*
 * 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.el.EL;
import woolpack.fn.Fn;

/**
 * 委譲先で生成したオブジェクトを{@link Map}にキャッシュして
 * コンテキスト役に設定する{@link Fn}です。
 * @author nakamura
 *
 * @param <C>
 * @param <K>
 */
public class SideEffectMapCache<C, K> implements Fn<C, Void> {
	private Fn<? super C, ? extends Map<? super K, Object>> mapGetter;
	private Fn<? super C, ? extends K> keyGetter;
	private Fn<? super C, ?> maker;
	private EL el;
	
	public SideEffectMapCache(
			final Fn<? super C, ? extends Map<? super K, Object>> mapGetter,
			final Fn<? super C, ? extends K> keyGetter,
			final Fn<? super C, ?> maker,
			final EL el) {
		this.mapGetter = mapGetter;
		this.keyGetter = keyGetter;
		this.maker = maker;
		this.el = el;
	}

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

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