/*
 * 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;
import woolpack.typeconvert.TypeConvertUtils;

/**
 * {@link Map}のみをサポートする式言語です。
 * 
 * @author nakamura
 * 
 */
public class MapEL extends AbstractEL {
	private String key;
	private Fn<ConvertContext, Void, ? extends RuntimeException> fn;

	/**
	 * @param key キー。
	 * @param fn 型を変換する関数。
	 */
	public MapEL(final String key, final Fn<ConvertContext, Void, ? extends RuntimeException> fn) {
		super();
		this.key = key;
		this.fn = fn;
	}

	/**
	 * @param key キー。
	 */
	public MapEL(final String key) {
		this(key, TypeConvertUtils.COLLECTION_CONVERTER);
	}

	@Override
	public boolean setValue(final Object root, final Object value) {
		final ConvertContext context = new ConvertContext();
		context.setPropertyName(key);
		context.setToType(Object.class);
		context.setValue(value);
		fn.exec(context);
		((Map) root).put(key, context.getValue());
		return true;
	}

	@Override
	public Object getValue(final Object root, final Class toType) {
		final Object result = ((Map) root).get(key);

		final ConvertContext context = new ConvertContext();
		context.setPropertyName(key);
		context.setToType(toType);
		context.setValue(result);
		fn.exec(context);
		return context.getValue();
	}

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