/*
 * 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.el.convert.ConvertConstants;
import woolpack.el.convert.Convertable;

/**
 * {@link Map}のみをサポートする{@link EL}。
 * @author nakamura
 *
 */
public class MapEL extends ELAdapter {
	private final String key;
	private final Convertable convertable;
	
	/**
	 * コンストラクタ。
	 * @param key キー。
	 * @param convertable 変換器。
	 * @throws NullPointerException 引数のいずれかが null の場合。
	 * @throws StringIndexOutOfBoundsException key が空の場合。
	 */
	public MapEL(final String key, final Convertable convertable){
		key.charAt(0);
		convertable.getClass();
		
		this.key = key;
		this.convertable = convertable;
	}

	/**
	 * コンストラクタ。
	 * @param key キー。
	 * @throws NullPointerException 引数が null の場合。
	 * @throws StringIndexOutOfBoundsException 引数が空の場合。
	 */
	public MapEL(final String key){
		this(key, ConvertConstants.COLLECTION_CONVERTER);
	}

	@Override public void setValue(final Object root, final Object value)
			throws ELTargetRuntimeException {
		final Object newValue = convertable.convert(value, Object.class, key);
		((Map)root).put(key, newValue);
	}

	@Override public Object getValue(final Object root, final Class toType) throws ELTargetRuntimeException {
		final Object result = ((Map)root).get(key);
		return convertable.convert(result, toType, key);
	}

	public Convertable getConvertable() {
		return convertable;
	}

	public String getKey() {
		return key;
	}
}
