/*
 * Copyright 2014 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 uk.co.real_logic.aeron.driver;

import uk.co.real_logic.aeron.common.BitUtil;

import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

/**
 * Encapsulation of NIO Selector logic for integration into Receiver Thread and Conductor Thread
 */
public class NioSelector implements AutoCloseable
{
    private static final int ITERATION_THRESHOLD = 5;
    private static final int INITIAL_TRANSPORT_LIST_CAPACITY = BitUtil.findNextPositivePowerOfTwo(ITERATION_THRESHOLD);
    private static final Field SELECTED_KEYS_FIELD;
    private static final Field PUBLIC_SELECTED_KEYS_FIELD;

    static
    {
        Field selectKeysField = null;
        Field publicSelectKeysField = null;

        try
        {
            final Class<?> clazz = Class.forName("sun.nio.ch.SelectorImpl", false, ClassLoader.getSystemClassLoader());

            if (clazz.isAssignableFrom(Selector.open().getClass()))
            {
                selectKeysField = clazz.getDeclaredField("selectedKeys");
                selectKeysField.setAccessible(true);

                publicSelectKeysField = clazz.getDeclaredField("publicSelectedKeys");
                publicSelectKeysField.setAccessible(true);
            }
        }
        catch (final Exception ignore)
        {
        }

        SELECTED_KEYS_FIELD = selectKeysField;
        PUBLIC_SELECTED_KEYS_FIELD = publicSelectKeysField;
    }

    private final Selector selector;
    private final NioSelectedKeySet selectedKeySet;
    private final ArrayList<UdpChannelTransport> transportList = new ArrayList<>(INITIAL_TRANSPORT_LIST_CAPACITY);

    /**
     * Construct a selector
     */
    public NioSelector()
    {
        NioSelectedKeySet tmpSet = null;

        try
        {
            this.selector = Selector.open(); // yes, SelectorProvider, blah, blah
        }
        catch (final IOException ex)
        {
            throw new RuntimeException(ex);
        }

        if (null != PUBLIC_SELECTED_KEYS_FIELD)
        {
            try
            {
                tmpSet = new NioSelectedKeySet();

                SELECTED_KEYS_FIELD.set(selector, tmpSet);
                PUBLIC_SELECTED_KEYS_FIELD.set(selector, tmpSet);
            }
            catch (final Exception ignore)
            {
                tmpSet = null;
            }
        }

        selectedKeySet = tmpSet;
    }

    /**
     * Register channel for read.
     *
     * @param channel to select for read
     * @param udpChannelTransport to associate with read
     * @return SelectionKey for registration for cancel
     */
    public SelectionKey registerForRead(final SelectableChannel channel, final UdpChannelTransport udpChannelTransport)
    {
        try
        {
            transportList.add(udpChannelTransport);
            return channel.register(selector, SelectionKey.OP_READ, udpChannelTransport);
        }
        catch (final ClosedChannelException ex)
        {
            throw new RuntimeException(ex);
        }
    }

    /**
     * Cancel previous registration.
     *
     * @param udpChannelTransport to cancel read for
     */
    public void cancelRead(final UdpChannelTransport udpChannelTransport)
    {
        transportList.remove(udpChannelTransport);
    }

    /**
     * Close NioSelector down. Returns immediately.
     */
    public void close()
    {
        selector.wakeup();
        try
        {
            selector.close();
        }
        catch (final IOException ex)
        {
            throw new RuntimeException(ex);
        }
    }

    /**
     * Explicit event loop processing as a poll
     *
     * @return the number of frames processed.
     */
    public int processKeys()
    {
        try
        {
            int handledFrames = 0;

            if (transportList.size() <= ITERATION_THRESHOLD)
            {
                for (int i = transportList.size() - 1; i >= 0; i--)
                {
                    handledFrames += transportList.get(i).attemptReceive();
                }
            }
            else
            {
                selector.selectNow();

                if (null != PUBLIC_SELECTED_KEYS_FIELD)
                {
                    final SelectionKey[] keys = selectedKeySet.keys();

                    for (int i = selectedKeySet.size() - 1; i >= 0; i--)
                    {
                        final SelectionKey key = keys[i];

                        handledFrames += ((UdpChannelTransport) key.attachment()).attemptReceive();
                    }

                    selectedKeySet.reset();
                }
                else
                {
                    handledFrames = handleSelectedKeys();
                }
            }

            return handledFrames;
        }
        catch (final IOException ex)
        {
            throw new RuntimeException(ex);
        }
    }

    /**
     * Explicit call to selectNow but without processing of selected keys.
     */
    public void selectNowWithoutProcessing()
    {
        try
        {
            selector.selectNow();
        }
        catch (final IOException ex)
        {
            throw new RuntimeException(ex);
        }
    }

    private int handleSelectedKeys()
    {
        int handledFrames = 0;
        final Set<SelectionKey> selectedKeys = selector.selectedKeys();
        final Iterator<SelectionKey> iter = selectedKeys.iterator();

        while (iter.hasNext())
        {
            final SelectionKey key = iter.next();
            if (key.isReadable())
            {
                handledFrames += ((UdpChannelTransport)key.attachment()).attemptReceive();
            }

            iter.remove();
        }

        return handledFrames;
    }
}

@@ -5875,24 +5875,132 @@
 electNow();%0A
+            if (null != selectedKeySet)%0A            %7B%0A                selectedKeySet.reset();%0A            %7D%0A
         %7D%0A  

make sure to reset key set when calling selectNowWithoutProcessing