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

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

/**
 * 委譲先で生成した{@link GettingEL}と{@link EL}をクラス名とプロパティ名をーキーとしてキャッシュする{@link PropertyELFactory}。
 * 適用しているパターン：Proxy。
 * @author nakamura
 *
 */
public class CachePropertyELFactory implements PropertyELFactory {
	private static final Map<Class,Map<String,GettingEL>> getterMap = new HashMap<Class,Map<String,GettingEL>>();
	private static final Map<Class,Map<String,EL>> setterMap = new HashMap<Class,Map<String,EL>>();
	
	private final PropertyELFactory factory;
	
	/**
	 * コンストラクタ。
	 * @param factory 委譲先。
	 * @throws NullPointerException 引数が null の場合。
	 */
	public CachePropertyELFactory(final PropertyELFactory factory){
		factory.getClass();
		this.factory = factory;
	}

	public GettingEL newGetter(final Class clazz, final String propertyName) {
		GettingEL getter = null;
		{
			Map<String,GettingEL> map1 = getterMap.get(clazz);
			if(map1 != null){
				getter = map1.get(propertyName);
			}
			if(getter == null){
				getter = factory.newGetter(clazz, propertyName);
				if(map1 == null){
					map1 = new HashMap<String,GettingEL>();
					getterMap.put(clazz, map1);
				}
				map1.put(propertyName, getter);
			}
		}
		return getter;
	}

	public EL newSetter(final Class clazz, final String propertyName) {
		EL setter = null;
		{
			Map<String,EL> map1 = setterMap.get(clazz);
			if(map1 != null){
				setter = map1.get(propertyName);
			}
			if(setter == null){
				setter = factory.newSetter(clazz, propertyName);
				if(map1 == null){
					map1 = new HashMap<String,EL>();
					setterMap.put(clazz, map1);
				}
				map1.put(propertyName, setter);
			}
		}
		return setter;
	}

	public PropertyELFactory getFactory() {
		return factory;
	}
}
