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

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import woolpack.utils.CheckUtils;

/**
 * 委譲先で生成した{@link Updatable}をキャッシュする{@link UpdatableFactory}。
 * 適用しているパターン：Proxy。
 * @author nakamura
 *
 */
public class UpdatableFactoryCacheImpl implements UpdatableFactory {
	private final Map<Object, Updatable> cacheMap;
	private final UpdatableFactory factory;
	
	/**
	 * コンストラクタ。
	 * @param cacheMap キャッシュ。本クラスはこの引数の状態を変化させる。
	 * null が指定された場合はキャッシュを行わない。
	 * @param factory 委譲先。
	 * @throws NullPointerException factory が null の場合。
	 */
	public UpdatableFactoryCacheImpl(
			final Map<Object, Updatable> cacheMap,
			final UpdatableFactory factory) {
		CheckUtils.checkNotNull(factory);
		this.cacheMap = cacheMap;
		this.factory = factory;
	}

	public Updatable newInstance(final String id, final Map<String, List<Object>> map) {
		if (cacheMap == null) {
			return factory.newInstance(id, map);
		} else {
			final Map<String, Object> key = new HashMap<String, Object>(2);
			key.put("name", id);
			key.put("columnSet", map.keySet());
			
			Updatable updatable = cacheMap.get(key);
			if (updatable == null) {
				updatable = factory.newInstance(id, map);
				cacheMap.put(key, updatable);
			}
			return updatable;
		}
	}
}
