/*
 * 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.Fn;
import woolpack.utils.Utils;

/**
 * 一覧型を変換する{@link Fn}です。
 * 
 * @author nakamura
 * 
 */
public class CollectionConverter implements Fn<ConvertContext, Void> {
	private Fn<ConvertContext, Void> fn;

	/**
	 * @param fn 単純型を変換するための委譲先。
	 */
	public CollectionConverter(final Fn<ConvertContext, Void> fn) {
		this.fn = fn;
	}

	public Void exec(final ConvertContext c) {
		final Collection collection = Utils.toCollection(c.getValue());
		if (c.getToType().isArray()) {
			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);
					fn.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);
				}
			}
		} else if (Collection.class.isAssignableFrom(c.getToType())) {
			c.setValue(collection);
		} else {
			c.setValue(collection.iterator().next());
			fn.exec(c);
		}
		return null;
	}

	public Fn<ConvertContext, Void> getFn() {
		return fn;
	}
	public void setFn(final Fn<ConvertContext, Void> fn) {
		this.fn = fn;
	}
}
