package cc.redberry.pipe.blocks;

import cc.redberry.pipe.OutputPort;
import cc.redberry.pipe.Processor;
import org.junit.Assert;
import org.junit.Test;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

public class ResultAttachingProcessorTest {
    @Test
    public void test0() throws InterruptedException {
        Generator gen = new Generator();
        Proc proc = new Proc();
        OutputPort<InputOutputPair<Integer, Integer>> values =
                new ParallelProcessor<>(gen, new ResultAttachingProcessor<Integer, Integer>(proc), 1000, 10);

        InputOutputPair<Integer, Integer> i;
        while ((i = values.take()) != null) {
            Assert.assertEquals((long) (i.input * 4 - 1), (long) i.result);
        }
    }

    private static class Proc implements Processor<Integer, Integer> {
        @Override
        public Integer process(Integer input) {
            return input * 4 - 1;
        }
    }

    private static class Generator implements OutputPort<Integer> {
        private final AtomicInteger counter = new AtomicInteger(1000);

        private Generator() {
        }

        public synchronized Integer take() {
            if (counter.decrementAndGet() < 0)
                return null;
            return ThreadLocalRandom.current().nextInt(10000);
        }
    }
}
