/*
 * cc.redberry.concurrent: high-level Java concurrent library.
 * Copyright (c) 2010-2012
 * Bolotin Dmitriy <bolotin.dmitriy@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU 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 General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package cc.redberry.pipe.blocks;


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

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ParallelProcessorTest {
    private static final int count = 100000;

    @Test
    public void testSimpleExecutorService() {
        ExecutorService es = Executors.newCachedThreadPool();
        try {
            TProcessor p = new TProcessor();
            ParallelProcessor<IntPair, IntPair> cp = new ParallelProcessor<IntPair, IntPair>(new Generator(), p, 100, 40, es);
            int i = 0;
            while (true) {
                IntPair pair = cp.take();
                if (pair == null) {
                    Assert.assertTrue(i == count);
                    return;
                }
                ++i;
                Assert.assertTrue(pair.result == pair.value + pair.value * pair.value / 3);
            }
        } finally {
            es.shutdownNow();
        }
    }

    @Test
    public void testSimpleThreads() {
        TProcessor p = new TProcessor();
        ParallelProcessor<IntPair, IntPair> cp = new ParallelProcessor<IntPair, IntPair>(new Generator(), p, 100, 40);
        int i = 0;
        try {
            while (true) {
                IntPair pair = cp.take();
                if (pair == null) {
                    Assert.assertTrue(i == count);
                    return;
                }
                ++i;
                Assert.assertTrue(pair.result == pair.value + pair.value * pair.value / 3);
            }
        } catch (PInterruptedException ex) {
            Logger.getLogger(ParallelProcessorTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Test
    public void testCloseExecutorService0() {
        ExecutorService es = Executors.newCachedThreadPool();
        try {
            TProcessor p = new TProcessor();
            final Generator generator = new Generator(Integer.MAX_VALUE);
            final ParallelProcessor<IntPair, IntPair> cp =
                    new ParallelProcessor<IntPair, IntPair>(generator, p, 100, 40, es);
            //cp.setFailSafe(true);
            int i = 0;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(100);
                        cp.close();
                    } catch (InterruptedException e) {
                    }
                }
            }).start();

            while (true) {
                IntPair pair = cp.take();
                if (pair == null) {
                    Assert.assertTrue(i <= generator.i);
                    return;
                }
                ++i;
                Assert.assertTrue(pair.result == pair.value + pair.value * pair.value / 3);
            }
        } finally {
            Assert.assertEquals(es.shutdownNow().size(), 0); //All threads stopped.
        }
    }

    @Test
    public void testCloseExecutorService1() {
        ExecutorService es = Executors.newCachedThreadPool();
        try {
            TProcessor p = new TProcessor();
            final Generator generator = new Generator(Integer.MAX_VALUE);
            final ParallelProcessor<IntPair, IntPair> cp =
                    new ParallelProcessor<IntPair, IntPair>(generator, p, 100, 40, es)
                            .setFailSafe(true);
            int i = 0;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(100);
                        cp.close();
                    } catch (InterruptedException e) {
                    }
                }
            }).start();

            while (true) {
                IntPair pair = cp.take();
                if (pair == null) {
                    Assert.assertEquals(i, generator.i);
                    return;
                }
                ++i;
                Assert.assertTrue(pair.result == pair.value + pair.value * pair.value / 3);
            }
        } finally {
            Assert.assertEquals(es.shutdownNow().size(), 0); //All threads stopped.
        }
    }

    @Test
    public void testCloseThread1() {
        TProcessor p = new TProcessor();
        final Generator generator = new Generator(Integer.MAX_VALUE);
        final ParallelProcessor<IntPair, IntPair> cp =
                new ParallelProcessor<IntPair, IntPair>(generator, p, 100, 40)
                        .setFailSafe(true);
        int i = 0;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100);
                    cp.close();
                } catch (InterruptedException e) {
                }
            }
        }).start();

        while (true) {
            IntPair pair = cp.take();
            if (pair == null) {
                Assert.assertEquals(i, generator.i);
                return;
            }
            ++i;
            Assert.assertTrue(pair.result == pair.value + pair.value * pair.value / 3);
        }
    }

    @Test(expected = RuntimeException.class)
    public void testExceptionExecutorService() {
        ExecutorService es = Executors.newCachedThreadPool();
        try {
            TProcessorException p = new TProcessorException();
            ParallelProcessor<IntPair, IntPair> cp = new ParallelProcessor<IntPair, IntPair>(new Generator(Integer.MAX_VALUE), p, 100, 40, es);
            int i = 0;
            while (true) {
                IntPair pair = cp.take();
                if (pair == null) {
                    break;
                }
                ++i;
                Assert.assertTrue(pair.result == pair.value + pair.value * pair.value / 3);
            }
        } finally {
            es.shutdownNow();
        }
    }

    @Test(expected = RuntimeException.class)
    public void testExceptionThread() {
        try {
            TProcessorException p = new TProcessorException();
            ParallelProcessor<IntPair, IntPair> cp = new ParallelProcessor<IntPair, IntPair>(new Generator(Integer.MAX_VALUE), p, 100, 40);
            int i = 0;
            while (true) {
                IntPair pair = cp.take();
                if (pair == null) {
                    break;
                }
                ++i;
                Assert.assertTrue(pair.result == pair.value + pair.value * pair.value / 3);
            }
            cp.join();
        } catch (InterruptedException ex) {
            throw new RuntimeException(ex);
        }
    }

    private static class IntPair {
        public int value, result;

        public IntPair(int value) {
            this.value = value;
        }
    }

    private static class Generator implements OutputPort<IntPair> {
        private final int count;
        private Random random = new Random();
        private int i = 0;

        private Generator() {
            this.count = ParallelProcessorTest.count;
        }

        private Generator(int count) {
            this.count = count;
        }

        public synchronized IntPair take() {
            int val = random.nextInt(100);
            if (i++ > count - 1)
                return null;
            return new IntPair(val);
        }
    }

    private static class TProcessor implements Processor<IntPair, IntPair> {
        public IntPair process(IntPair input) {
            input.result = input.value + input.value * input.value / 3;
            return input;
        }
    }

    private static class TProcessorException implements Processor<IntPair, IntPair> {
        public IntPair process(IntPair input) {
            if (input.value == 42)
                throw new TestException();
            input.result = input.value + input.value * input.value / 3;
            return input;
        }
    }

    private static class TestException extends RuntimeException {
    }
}