/*
 * 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.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

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

/**
 * {@link List}、{@link Collection}、{@link Iterable}に変換する関数です。
 * 変換前オブジェクトと変換後オブジェクトが相互に影響するかはパッケージに説明しています。
 * <br/>適用しているデザインパターン：Chain of Responsibility。
 * @author nakamura
 * 
 */
public class ToCollectionViewConverter extends Delegator<ConvertContext, Void, RuntimeException> {

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

	private Object copy(final Object before, final Collection<Object> after) {
		for(final Object element : (Iterable) before) {
			after.add(element);
		}
		return after;
	}

	@Override
	public Void exec(final ConvertContext c) {
		final Class<?> toType = c.getToType();
		final Object before = c.getValue();
		if (List.class.isAssignableFrom(toType)) {
			if (before.getClass().isArray()) {
				c.setValue(Utils.arrayToList(before));
				return null;
			}
		} else if (Set.class.isAssignableFrom(toType)) {
			if (before.getClass().isArray()) {
				c.setValue(new LinkedHashSet<Object>(Utils.arrayToList(before)));
			} else if (before instanceof Iterable){
				c.setValue(copy(before, new LinkedHashSet<Object>()));
			} else {
				c.setValue(Collections.singleton(before));
			}
			return null;
		} else if (Collection.class.isAssignableFrom(toType)) {
			// nothing to do.
		} else if (Iterable.class.isAssignableFrom(toType)) {
			// nothing to do.
		} else {
			super.exec(c);
			return null;
		}
		if (before.getClass().isArray()) {
			c.setValue(new ArrayList<Object>(Utils.arrayToList(before)));
		} else if (before instanceof Iterable){
			c.setValue(copy(before, new ArrayList<Object>()));
		} else {
			c.setValue(Collections.singletonList(before));
		}
		return null;
	}
}
