/*
 * Copyright 2014 - 2016 Real Logic Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.aeron;

import io.aeron.driver.MediaDriver;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import io.aeron.driver.ThreadingMode;
import io.aeron.logbuffer.FragmentHandler;
import io.aeron.logbuffer.Header;
import io.aeron.protocol.DataHeaderFlyweight;
import org.agrona.BitUtil;
import org.agrona.DirectBuffer;
import org.agrona.concurrent.UnsafeBuffer;

import java.util.concurrent.TimeUnit;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

public class PongTest
{
    public static final String PING_URI = "aeron:udp?endpoint=localhost:54325";
    public static final String PONG_URI = "aeron:udp?endpoint=localhost:54326";

    private static final int PING_STREAM_ID = 1;
    private static final int PONG_STREAM_ID = 2;
    private static final ThreadingMode THREADING_MODE = ThreadingMode.SHARED;

    private final MediaDriver.Context context = new MediaDriver.Context();
    private final Aeron.Context pingAeronContext = new Aeron.Context();
    private final Aeron.Context pongAeronContext = new Aeron.Context();

    private Aeron pingClient;
    private Aeron pongClient;
    private MediaDriver driver;
    private Subscription pingSubscription;
    private Subscription pongSubscription;
    private Publication pingPublication;
    private Publication pongPublication;

    private UnsafeBuffer buffer = new UnsafeBuffer(new byte[4096]);
    private FragmentHandler pongHandler = mock(FragmentHandler.class);

    @Before
    public void setUp() throws Exception
    {
        context.threadingMode(THREADING_MODE);

        driver = MediaDriver.launch(context);
        pingClient = Aeron.connect(pingAeronContext);
        pongClient = Aeron.connect(pongAeronContext);

        pingPublication = pingClient.addPublication(PING_URI, PING_STREAM_ID);
        pingSubscription = pongClient.addSubscription(PING_URI, PING_STREAM_ID);

        pongPublication = pongClient.addPublication(PONG_URI, PONG_STREAM_ID);
        pongSubscription = pingClient.addSubscription(PONG_URI, PONG_STREAM_ID);
    }

    @After
    public void closeEverything() throws Exception
    {
        if (null != pingPublication)
        {
            pingPublication.close();
        }

        if (null != pongPublication)
        {
            pongPublication.close();
        }

        if (null != pingSubscription)
        {
            pingSubscription.close();
        }

        if (null != pongSubscription)
        {
            pongSubscription.close();
        }

        pongClient.close();
        pingClient.close();
        driver.close();

        context.deleteAeronDirectory();
    }

    @Test
    public void playPingPong()
    {
        buffer.putInt(0, 1);

        while (pingPublication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L)
        {
            Thread.yield();
        }

        final int fragmentsRead[] = new int[1];

        SystemTestHelper.executeUntil(
            () -> fragmentsRead[0] > 0,
            (i) ->
            {
                fragmentsRead[0] += pingSubscription.poll(this::pingHandler, 10);
                Thread.yield();
            },
            Integer.MAX_VALUE,
            TimeUnit.MILLISECONDS.toNanos(5900));

        fragmentsRead[0] = 0;

        SystemTestHelper.executeUntil(
            () -> fragmentsRead[0] > 0,
            (i) ->
            {
                fragmentsRead[0] += pongSubscription.poll(pongHandler, 10);
                Thread.yield();
            },
            Integer.MAX_VALUE,
            TimeUnit.MILLISECONDS.toNanos(5900));

        verify(pongHandler).onFragment(
            any(DirectBuffer.class),
            eq(DataHeaderFlyweight.HEADER_LENGTH),
            eq(BitUtil.SIZE_OF_INT),
            any(Header.class));
    }

    public void pingHandler(final DirectBuffer buffer, final int offset, final int length, final Header header)
    {
        // echoes back the ping
        while (pongPublication.offer(buffer, offset, length) < 0L)
        {
            Thread.yield();
        }
    }
}

@@ -1023,16 +1023,66 @@
 imeUnit;
+%0Aimport java.util.concurrent.atomic.AtomicInteger;
 %0A%0Aimport
@@ -2898,392 +2898,8 @@
   %7B%0A
-        if (null != pingPublication)%0A        %7B%0A            pingPublication.close();%0A        %7D%0A%0A        if (null != pongPublication)%0A        %7B%0A            pongPublication.close();%0A        %7D%0A%0A        if (null != pingSubscription)%0A        %7B%0A            pingSubscription.close();%0A        %7D%0A%0A        if (null != pongSubscription)%0A        %7B%0A            pongSubscription.close();%0A        %7D%0A%0A
     
@@ -3237,19 +3237,29 @@
   final 
-int
+AtomicInteger
  fragmen
@@ -3268,23 +3268,30 @@
 Read
-%5B%5D
  = new 
-int%5B1%5D
+AtomicInteger()
 ;%0A%0A 
@@ -3351,35 +3351,38 @@
 -%3E fragmentsRead
-%5B0%5D
+.get()
  %3E 0,%0A          
@@ -3433,23 +3433,27 @@
 entsRead
-%5B0%5D += 
+.addAndGet(
 pingSubs
@@ -3480,32 +3480,33 @@
 pingHandler, 10)
+)
 ;%0A              
@@ -3645,15 +3645,15 @@
 Read
-%5B0%5D = 0
+.set(0)
 ;%0A%0A 
@@ -3721,19 +3721,22 @@
 entsRead
-%5B0%5D
+.get()
  %3E 0,%0A  
@@ -3799,15 +3799,19 @@
 Read
-%5B0%5D += 
+.addAndGet(
 pong
@@ -3844,16 +3844,17 @@
 ler, 10)
+)
 ;%0A      

Fix concurrency issues with fragment reporting in system tests and tidy up.