/*
 * Copyright (C) 2013 The enviroCar project
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.envirocar.server.core.util;

import java.util.Iterator;

import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;

/**
 * TODO JavaDoc
 *
 * @author Christian Autermann <autermann@uni-muenster.de>
 */
public class UpCastingIterable<T> extends PaginatedIterable<T> {
    private final Iterable<? extends T> delegate;

    public UpCastingIterable(Iterable<? extends T> delegate,
                             Pagination pagination, long elements) {
        super(pagination, elements);
        Preconditions.checkNotNull(delegate);
        this.delegate = delegate;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Iterator<T> iterator() {
        return (Iterator<T>) delegate.iterator();
    }

    @Override
    public String toString() {
        return Joiner.on(", ").appendTo(new StringBuilder()
                .append(getClass().getSimpleName())
                .append('['), iterator()).append(']').toString();
    }
}

@@ -781,16 +781,68 @@
 terator;
+%0Aimport java.util.LinkedList;%0Aimport java.util.List;
 %0A%0Aimport
@@ -1119,16 +1119,50 @@
 elegate;
+%0A    private List%3CT%3E items = null;
 %0A%0A    pu
@@ -1506,49 +1506,721 @@
     
-return (Iterator%3CT%3E) delegate.iterator();
+if (items == null) %7B%0A            items = new LinkedList%3CT%3E();%0A            return new Iterator%3CT%3E() %7B%0A                private final Iterator%3C? extends T%3E it = delegate.iterator();%0A%0A                @Override%0A                public boolean hasNext() %7B%0A                    return it.hasNext();%0A                %7D%0A%0A                @Override%0A                public T next() %7B%0A                    T t = it.next();%0A                    items.add(t);%0A                    return t;%0A                %7D%0A%0A                @Override%0A                public void remove() %7B%0A                    throw new UnsupportedOperationException();%0A                %7D%0A            %7D;%0A        %7D else %7B%0A            return items.iterator();%0A        %7D
 %0A   

save iterator results for one-time iterables