/*
 * 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}です。
 * 
 * @author nakamura
 * 
 */
public class CachePropertyELFactory implements PropertyELFactory {
	private static final Map<Class, Map<String, GettingEL>> GETTER_MAP
	= new HashMap<Class, Map<String, GettingEL>>();

	private static final Map<Class, Map<String, EL>> SETTER_MAP
	= new HashMap<Class, Map<String, EL>>();

	private PropertyELFactory factory;

	public CachePropertyELFactory(final PropertyELFactory factory) {
		this.factory = factory;
	}

	public GettingEL newGetter(final Class clazz, final String propertyName) {
		GettingEL getter = null;
		{
			Map<String, GettingEL> map1 = GETTER_MAP.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>();
					GETTER_MAP.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 = SETTER_MAP.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>();
					SETTER_MAP.put(clazz, map1);
				}
				map1.put(propertyName, setter);
			}
		}
		return setter;
	}

	public PropertyELFactory getFactory() {
		return factory;
	}
	public void setFactory(final PropertyELFactory factory) {
		this.factory = factory;
	}
}
