/*
 * 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.lang.reflect.Array;
import java.util.Collection;

import woolpack.fn.Delegator;
import woolpack.fn.Fn;
import woolpack.utils.Utils;

/**
 * 配列に変換する関数です。
 * 配列の各要素を{@link ConvertContext#getFn()}で変換します。
 * 変換後の状態変化と変換前の状態変化は相互に伝播しません。
 * <br/>適用しているデザインパターン：Chain of Responsibility。
 * @author nakamura
 * 
 */
public class ToArrayConverter extends Delegator<ConvertContext, Void, RuntimeException> {

	/**
	 * @param fn {@link ConvertContext#getToType()}が配列でない場合の委譲先。
	 */
	public ToArrayConverter(
			final Fn<? super ConvertContext, Void, ? extends RuntimeException> fn) {
		super(fn);
	}

	@Override
	public Void exec(final ConvertContext c) {
		if (!c.getToType().isArray()) {
			super.exec(c);
			return null;
		}
		final Collection<?> collection = Utils.toCollection(c.getValue());
		final Class baseToType = c.getToType();
		final Object baseValue = c.getValue();
		boolean successFlag = false;
		
		try {
			final Class componentType = baseToType.getComponentType();
			c.setToType(componentType);
			final boolean primitiveFlag = componentType.isPrimitive();
			final Object afterArray = Array.newInstance(componentType, collection.size());
			int i = 0;
			for (final Object before : collection) {
				c.setValue(before);
				c.getFn().exec(c);
				if (!primitiveFlag || c.getValue() != null) {
					// 値が null でプリミティブの場合は値を設定しません(配列作成時の初期値のまま)。
					Array.set(afterArray, i, c.getValue());
				}
				i++;
			}
			successFlag = true;
			c.setValue(afterArray);
		} finally {
			c.setToType(baseToType);
			if (!successFlag) {
				c.setValue(baseValue);
			}
		}
		return null;
	}
}
