/*
 * 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 woolpack.fn.Fn;

/**
 * 元のプロパティ名から類推したプロパティ名の候補を試行するプロパティ式言語ファクトリです。
 * @author nakamura
 * 
 */
public class SimilarPropertyELFactory implements PropertyELFactory {
	private PropertyELFactory factory;
	private Fn<String, Iterable<String>, ? extends RuntimeException> guessFactory;

	/**
	 * @param factory 委譲先。
	 * @param guessFactory 属性名に対応するプロパティ名の候補を列挙する{@link Iterable}のファクトリ。
	 */
	public SimilarPropertyELFactory(
			final PropertyELFactory factory,
			final Fn<String, Iterable<String>, ? extends RuntimeException> guessFactory) {
		this.factory = factory;
		this.guessFactory = guessFactory;
	}

	public GettingEL newGetter(final Class clazz, final String propertyName) {
		PropertyNotFoundException e0 = null;
		for (final String s : guessFactory.exec(propertyName)) {
			try {
				return factory.newGetter(clazz, s);
			} catch (final PropertyNotFoundException e1) {
				if (e0 == null) {
					e0 = e1;
				}
			}
		}
		throw e0;
	}

	public EL newSetter(final Class clazz, final String propertyName) {
		PropertyNotFoundException e0 = null;
		for (final String s : guessFactory.exec(propertyName)) {
			try {
				return factory.newSetter(clazz, s);
			} catch (final PropertyNotFoundException e1) {
				if (e0 == null) {
					e0 = e1;
				}
			}
		}
		throw e0;
	}

	public PropertyELFactory getFactory() {
		return factory;
	}
	public void setFactory(final PropertyELFactory factory) {
		this.factory = factory;
	}
	public Fn<String, Iterable<String>, ? extends RuntimeException> getGuessFactory() {
		return guessFactory;
	}
	public void setGuessFactory(
			final Fn<String, Iterable<String>, ? extends RuntimeException> guessFactory) {
		this.guessFactory = guessFactory;
	}
}
