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

import java.util.Map;

import woolpack.fn.Fn;

/**
 * Beanに変換する関数です。
 * 変換元の型がMapの場合は各プロパティを{@link ConvertContext#getFn()}で変換します。
 * 変換元の型が別のBeanの場合は各プロパティを{@link ConvertContext#getFn()}で変換します。
 * 変換後の状態変化と変換前の状態変化は相互に伝播しません。
 * @author nakamura
 * 
 */
public class ToBeanConverter implements Fn<ConvertContext, Void, RuntimeException> {
	public Void exec(final ConvertContext c) {
		final Object afterObject;
		try {
			afterObject = c.getToType().newInstance();
		} catch (final InstantiationException e) {
			throw new IllegalArgumentException(e);
		} catch (IllegalAccessException e) {
			throw new IllegalArgumentException(e);
		}
		final Map beforeMap;
		if (c.getValue() instanceof Map) {
			beforeMap = (Map) c.getValue();
		} else {
			beforeMap = new BeanMap(afterObject, c.getFn());
		}
		final Map<String, Object> afterMap = new BeanMap(afterObject, c.getFn());
		for (final String s : afterMap.keySet()) {
			afterMap.put(s, beforeMap.get(s));
		}
		c.setValue(afterObject);
		return null;
	}
}
