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

	public Query 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());
			
			Query query = cacheMap.get(key);
			if (query == null) {
				query = factory.newInstance(id, map);
				cacheMap.put(key, query);
			}
			return query;
		}
	}
}
