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

import woolpack.fn.Fn;
import woolpack.typeconvert.ConvertContext;

/**
 * {@link #newGetter(Class, String)}で
 * 元のプロパティ名から類推したプロパティ名の候補を試行する
 * {@link MapPropertyELFactory}です。
 * @author nakamura
 * 
 */
public class MapSimilarPropertyELFactory extends MapPropertyELFactory {
	private Fn<String, Iterable<String>, ? extends RuntimeException> guessFactory;

	/**
	 * @param fn 型を変換する関数。
	 * @param factory 型が{@link Map}でない場合の委譲先。
	 * @param guessFactory 属性名に対応するプロパティ名の候補を列挙する{@link Iterable}のファクトリ。
	 */
	public MapSimilarPropertyELFactory(
			final Fn<ConvertContext, Void, ? extends RuntimeException> fn,
			final PropertyELFactory factory,
			final Fn<String, Iterable<String>, ? extends RuntimeException> guessFactory) {
		super(fn, factory);
		this.guessFactory = guessFactory;
	}

	@Override
	public GettingEL newGetter(final Class clazz, final String propertyName) {
		if (Map.class.isAssignableFrom(clazz)) {
			return new AbstractGettingEL() {
				@Override
				public Object getValue(final Object root, final Class toType) {
					for (final String s : guessFactory.exec(propertyName)) {
						final Object result = ((Map) root).get(s);
						if (result != null) {
							final ConvertContext context = new ConvertContext();
							context.setPropertyName(s);
							context.setToType(toType);
							context.setValue(result);
							getFn().exec(context);
							return context.getValue();
						}
					}
					return null;
				}
			};
		}
		return getFactory().newGetter(clazz, propertyName);
	}

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