/*
 * 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 org.junit.Assert;
import org.junit.Test;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

public class MergerTest {
    public static final int THREADS = 20;

    @Test
    public void simpleTestThreads() throws InterruptedException {
        RandomGenerator[] rgs = new RandomGenerator[THREADS];
        for (int i = 0; i < THREADS; ++i)
            rgs[i] = new RandomGenerator(1000);

        Merger<Integer> merger = new Merger<>(1000);

        for (int i = 0; i < THREADS; ++i)
            merger.merge(rgs[i]);

        merger.start();

        long sum = 0;
        Integer value;
        while ((value = merger.take()) != null) {
            sum += value;
        }

        Assert.assertTrue(sum > 0);

        for (int i = 0; i < THREADS; ++i)
            sum -= rgs[i].sum.longValue();

        Assert.assertEquals(sum, 0L);
    }

    @Test
    public void simpleTestExecutorService() throws InterruptedException {
        ExecutorService es = Executors.newCachedThreadPool();
        try {
            RandomGenerator[] rgs = new RandomGenerator[THREADS];
            for (int i = 0; i < THREADS; ++i)
                rgs[i] = new RandomGenerator(1000);

            Merger<Integer> merger = new Merger<>(1000);

            for (int i = 0; i < THREADS; ++i)
                merger.merge(rgs[i], es);

            merger.start();

            long sum = 0;
            Integer value;
            while ((value = merger.take()) != null) {
                sum += value;
            }

            Assert.assertTrue(sum > 0);

            for (int i = 0; i < THREADS; ++i)
                sum -= rgs[i].sum.longValue();

            Assert.assertEquals(sum, 0L);
        } finally {
            es.shutdownNow();
        }
    }

    @Test
    public void closeTest0() throws InterruptedException {
        ExecutorService es = Executors.newCachedThreadPool();
        try {
            RandomGenerator[] rgs = new RandomGenerator[THREADS];
            for (int i = 0; i < THREADS; ++i)
                rgs[i] = new RandomGenerator(Integer.MAX_VALUE);

            final Merger<Integer> merger = new Merger<>(1000);

            for (int i = 0; i < THREADS; ++i)
                merger.merge(rgs[i], es);

            merger.start();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(100);
                        merger.close();
                    } catch (InterruptedException e) {
                    }
                }
            }).start();

            long sum = 0;
            Integer value;
            while ((value = merger.take()) != null) {
                sum += value;
            }

            Assert.assertTrue(sum > 0); //Something was consumed

            for (int i = 0; i < THREADS; ++i) {
                sum -= rgs[i].sum.longValue();
            }

            Assert.assertTrue(sum <= 0L); //Some elements between producers and consumer were lost (elements that were in buffer when close() method was called)
        } finally {
            Assert.assertEquals(es.shutdownNow().size(), 0); //All threads stopped.
        }
    }

    @Test
    public void closeTest1() throws InterruptedException {
        ExecutorService es = Executors.newCachedThreadPool();
        try {
            RandomGenerator[] rgs = new RandomGenerator[THREADS];
            for (int i = 0; i < THREADS; ++i)
                rgs[i] = new RandomGenerator(Integer.MAX_VALUE);

            final Merger<Integer> merger = new Merger<>(1000);
            merger.setFailSafe(true);

            for (int i = 0; i < THREADS; ++i)
                merger.merge(rgs[i], es);

            merger.start();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(100);
                        merger.close();
                    } catch (InterruptedException e) {
                    }
                }
            }).start();

            long sum = 0;
            Integer value;
            while ((value = merger.take()) != null) {
                sum += value;
            }

            Assert.assertTrue(sum > 0); //Something was consumed

            for (int i = 0; i < THREADS; ++i) {
                sum -= rgs[i].sum.longValue();
            }

            Assert.assertEquals(sum, 0L);
        } finally {
            Assert.assertEquals(es.shutdownNow().size(), 0); //All threads stopped.
        }
    }

    @Test
    public void exceptionTest1() throws InterruptedException {
        ExecutorService es = Executors.newCachedThreadPool();
        try {
            ExceptionRandomGenerator[] rgs = new ExceptionRandomGenerator[THREADS];
            for (int i = 0; i < THREADS; ++i)
                rgs[i] = new ExceptionRandomGenerator();

            final Merger<Integer> merger = new Merger<>(1000);

            merger.setFailSafe(true);

            for (int i = 0; i < THREADS; ++i)
                merger.merge(rgs[i], es);

            merger.start();

            long sum = 0;
            boolean ex = false;
            try {
                Integer value;
                while ((value = merger.take()) != null) {
                    sum += value;
                }
            } catch (RuntimeException e) {
                ex = true;
            }

            Assert.assertTrue(ex);

            Assert.assertTrue(sum > 0); //Something was consumed

            for (int i = 0; i < THREADS; ++i) {
                sum -= rgs[i].sum.longValue();
            }

            Assert.assertEquals(sum, 0L);
        } finally {
            Assert.assertEquals(es.shutdownNow().size(), 0); //All threads stopped.
        }
    }

    @Test
    public void exceptionTest2() throws InterruptedException {
        ExceptionRandomGenerator[] rgs = new ExceptionRandomGenerator[THREADS];
        for (int i = 0; i < THREADS; ++i)
            rgs[i] = new ExceptionRandomGenerator();

        final Merger<Integer> merger = new Merger<>(1000);
        merger.setFailSafe(true);

        for (int i = 0; i < THREADS; ++i)
            merger.merge(rgs[i]);

        merger.start();

        long sum = 0;
        boolean ex = false;
        try {
            Integer value;
            while ((value = merger.take()) != null) {
                sum += value;
            }
        } catch (RuntimeException e) {
            ex = true;
        }

        Assert.assertTrue(ex);

        Assert.assertTrue(sum > 0); //Something was consumed

        for (int i = 0; i < THREADS; ++i) {
            sum -= rgs[i].sum.longValue();
        }

        Assert.assertEquals(sum, 0L);
    }

    private static class RandomGenerator implements OutputPort<Integer> {
        final Random random = new Random();
        final AtomicLong sum = new AtomicLong();
        final AtomicInteger limit;

        private RandomGenerator(int limit) {
            this.limit = new AtomicInteger(limit);
        }

        @Override
        public synchronized Integer take() {
            if (limit.decrementAndGet() <= 0)
                return null;
            int next = random.nextInt(100);
            sum.addAndGet(next);
            return next;
        }
    }

    private static class ExceptionRandomGenerator implements OutputPort<Integer> {
        final Random random = new Random();
        final AtomicLong sum = new AtomicLong();

        @Override
        public synchronized Integer take() {
            int next = random.nextInt(100);
            if (next == 42)
                throw new TestException();
            sum.addAndGet(next);
            return next;
        }
    }

    private static class TestException extends RuntimeException {
    }
}
