package pulley.transforms;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import pulley.A0;
import pulley.A1;
import pulley.Actions;
import pulley.Cons;
import pulley.Promise;
import pulley.Promises;
import pulley.Scheduler;
import pulley.Stream;
import pulley.StreamPromise;
import pulley.Transformer;
import pulley.util.Optional;

public class ToList {

    public static <T> Stream<List<T>> toList(Stream<T> stream) {
        Transformer<T, List<T>> transformer = new Transformer<T, List<T>>() {
            @Override
            public Promise<Optional<Cons<List<T>>>> transform(final Promise<Optional<Cons<T>>> p) {
                return new StreamPromise<List<T>>() {

                    @Override
                    public Optional<Cons<List<T>>> get() {
                        final List<T> list = Collections.synchronizedList(new ArrayList<T>());
                        A1<T> addToList = Actions.addToList(list);
                        Stream.forEach(p, addToList);
                        return Optional.of(Cons.cons(list, Promises.<Cons<List<T>>> empty()));
                    }

                    @Override
                    public A0 closeAction() {
                        return p.closeAction();
                    }

                    @Override
                    public Scheduler scheduler() {
                        return p.scheduler();
                    }
                };
            }
        };
        return stream.transform(transformer);
    }
}
@@ -118,17 +118,17 @@
 pulley.A
-0
+1
 ;%0Aimport
@@ -128,33 +128,52 @@
 %0Aimport pulley.A
-1
+bstractStreamPromise
 ;%0Aimport pulley.
@@ -267,67 +267,13 @@
 ey.S
-cheduler;%0Aimport pulley.Stream;%0Aimport pulley.StreamPromise
+tream
 ;%0Aim
@@ -642,16 +642,24 @@
 urn new 
+Abstract
 StreamPr
@@ -664,16 +664,19 @@
 Promise%3C
+T, 
 List%3CT%3E%3E
@@ -672,24 +672,25 @@
 T, List%3CT%3E%3E(
+p
 ) %7B%0A%0A       
@@ -1109,304 +1109,8 @@
  %7D%0A%0A
-                    @Override%0A                    public A0 closeAction() %7B%0A                        return p.closeAction();%0A                    %7D%0A%0A                    @Override%0A                    public Scheduler scheduler() %7B%0A                        return p.scheduler();%0A                    %7D%0A
     

use AbstractStreamPromise