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

import woolpack.el.EL;
import woolpack.fn.Fn;

/**
 * 委譲先で生成したオブジェクトを{@link ConcurrentMap}にキャッシュして
 * コンテキスト役に設定する{@link Fn}です。
 * {@link ConcurrentMap#putIfAbsent(Object, Object)}を使用して返却値の一意性を保証しますが、
 * ひとつの返却値に対応するインスタンス生成の委譲が複数回発生する可能性があります。
 * @author nakamura
 *
 * @param <C>
 * @param <K>
 * @param <E>
 */
public class SideEffectConcurrentMapCache<C, K, E extends Exception> implements Fn<C, Void, E> {
	private Fn<? super C, ? extends ConcurrentMap<? super K, Object>, ? extends E> mapGetter;
	private Fn<? super C, ? extends K, ? extends E> keyGetter;
	private Fn<? super C, ?, ? extends E> maker;
	private EL el;
	
	public SideEffectConcurrentMapCache(
			final Fn<? super C, ? extends ConcurrentMap<? super K, Object>, ? extends E> mapGetter,
			final Fn<? super C, ? extends K, ? extends E> keyGetter,
			final Fn<? super C, ?, ? extends E> maker,
			final EL el) {
		this.mapGetter = mapGetter;
		this.keyGetter = keyGetter;
		this.maker = maker;
		this.el = el;
	}

	public Void exec(final C c) throws E {
		final ConcurrentMap<? super K, Object> map = mapGetter.exec(c);
		final K key = keyGetter.exec(c);
		while (true) {
			final Object value = map.get(key);
			if (value == null) {
				maker.exec(c);
				map.putIfAbsent(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, ? 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 ConcurrentMap<? super K, Object>, ? extends E> getMapGetter() {
		return mapGetter;
	}
	public void setMapGetter(
			final Fn<? super C, ? extends ConcurrentMap<? super K, Object>, ? extends E> mapGetter) {
		this.mapGetter = mapGetter;
	}
}
