package jp.sourceforge.glad.collection;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;

import jp.sourceforge.glad.collection.closure.Closure;
import jp.sourceforge.glad.collection.iteration.IterableIterationHandler;
import jp.sourceforge.glad.collection.iteration.MapIterationHandler;
import jp.sourceforge.glad.collection.predicate.Predicate;

public class CollectionUtils {

    @SuppressWarnings("unchecked")
    public static <T> T toArray(Collection<?> c, Class<?> type) {
        int length = c.size();
        T result = (T) Array.newInstance(type, length);
        if (type.isPrimitive()) {
            Object[] a = c.toArray();
            for (int i = 0; i < length; ++i) {
                Array.set(result, i, a[i]);
            }
        } else {
            c.toArray((Object[]) result);
        }
        return result;
    }

    public static <T> void iterate(
            Iterable<T> iterable, Closure<T> callback) {
        new IterableIterationHandler<T>(iterable).iterate(callback);
    }

    public static <T> void iterate(
            Iterable<T> iterable, Predicate<T> callback) {
        new IterableIterationHandler<T>(iterable).iterate(callback);
    }

    public static <K, V> void iterate(
            Map<K, V> map, Closure<Map.Entry<K, V>> callback) {
        new MapIterationHandler<K, V>(map).iterate(callback);
    }

    public static <K, V> void iterate(
            Map<K, V> map, Predicate<Map.Entry<K, V>> callback) {
        new MapIterationHandler<K, V>(map).iterate(callback);
    }

}
