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

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

/**
 * 引数自身を返す式言語です。
 * 変換先クラスを指定することにより型変換を行わせることができます。
 * @author nakamura
 *
 */
public class ThisEL extends AbstractEL {
	private Fn<ConvertContext, Void, ? extends RuntimeException> fn;
	private String propertyName;
	
	/**
	 * 
	 * @param fn 型を変換する関数。
	 * @param propertyName 変換する際のプロパティ名。
	 */
	public ThisEL(
			final Fn<ConvertContext, Void, ? extends RuntimeException> fn,
			final String propertyName) {
		this.fn = fn;
		this.propertyName = propertyName;
	}

	@Override
	public Object getValue(final Object root, final Class toType) {
		final ConvertContext context = new ConvertContext();
		context.setPropertyName(propertyName);
		context.setToType(toType);
		context.setValue(root);
		fn.exec(context);
		return context.getValue();
	}
	
	@Override
	public boolean setValue(final Object root, final Object value) {
		final Map map; 
		{
			final ConvertContext context = new ConvertContext();
			context.setPropertyName(propertyName);
			context.setToType(Map.class);
			context.setValue(value);
			fn.exec(context);
			map = (Map) context.getValue();
		}
		for(final Object entryObject : map.entrySet()) {
			final Entry entry = (Entry) entryObject;
			ELUtils.EL_FACTORY
			.exec(entry.getKey().toString())
			.setValue(root, entry.getValue());
		}
		return true;
	}

	public Fn<ConvertContext, Void, ? extends RuntimeException> getFn() {
		return fn;
	}
	public void setFn(final Fn<ConvertContext, Void, ? extends RuntimeException> fn) {
		this.fn = fn;
	}
	public String getPropertyName() {
		return propertyName;
	}
	public void setPropertyName(final String propertyName) {
		this.propertyName = propertyName;
	}
}
