/*
 * Copyright 2016 The Netty Project
 *
 * The Netty Project licenses this file to you 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.netty.resolver;

import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
import io.netty.util.concurrent.Promise;
import io.netty.util.internal.UnstableApi;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * A {@link NameResolver} that resolves {@link InetAddress} and force Round Robin by choosing a single address
 * randomly in {@link #resolve(String)} and {@link #resolve(String, Promise)}
 * if multiple are returned by the {@link NameResolver}.
 * Use {@link #asAddressResolver()} to create a {@link InetSocketAddress} resolver
 */
@UnstableApi
public class RoundRobinInetAddressResolver extends InetNameResolver {
    private final NameResolver<InetAddress> nameResolver;
    private final AtomicInteger index = new AtomicInteger();

    /**
     * @param executor the {@link EventExecutor} which is used to notify the listeners of the {@link Future} returned by
     * {@link #resolve(String)}
     * @param nameResolver the {@link NameResolver} used for name resolution
     */
    public RoundRobinInetAddressResolver(EventExecutor executor, NameResolver<InetAddress> nameResolver) {
        super(executor);
        this.nameResolver = nameResolver;
    }

    @Override
    protected void doResolve(final String inetHost, final Promise<InetAddress> promise) throws Exception {
        // hijack the doResolve request, but do a doResolveAll request under the hood.
        // Note that InetSocketAddress.getHostName() will never incur a reverse lookup here,
        // because an unresolved address always has a host name.
        nameResolver.resolveAll(inetHost).addListener(new FutureListener<List<InetAddress>>() {
            @Override
            public void operationComplete(Future<List<InetAddress>> future) throws Exception {
                if (future.isSuccess()) {
                    List<InetAddress> inetAddresses = future.getNow();
                    int numAddresses = inetAddresses.size();
                    if (numAddresses > 0) {
                        // if there are multiple addresses: we shall pick one by one
                        // to support the round robin distribution
                        promise.setSuccess(inetAddresses.get(index.getAndIncrement() % numAddresses));
                    } else {
                        promise.setFailure(new UnknownHostException(inetHost));
                    }
                } else {
                    promise.setFailure(future.cause());
                }
            }
        });
    }

    @Override
    protected void doResolveAll(String inetHost, final Promise<List<InetAddress>> promise) throws Exception {
        nameResolver.resolveAll(inetHost).addListener(new FutureListener<List<InetAddress>>() {
            @Override
            public void operationComplete(Future<List<InetAddress>> future) throws Exception {
                if (future.isSuccess()) {
                    List<InetAddress> inetAddresses = future.getNow();
                    if (!inetAddresses.isEmpty()) {
                        // create a copy to make sure that it's modifiable random access collection
                        List<InetAddress> result = new ArrayList<InetAddress>(inetAddresses);
                        // rotate by different distance each time to force round robin distribution
                        Collections.rotate(result, index.getAndIncrement());
                        promise.setSuccess(result);
                    } else {
                        promise.setSuccess(inetAddresses);
                    }
                } else {
                    promise.setFailure(future.cause());
                }
            }
        });
    }
}

@@ -832,16 +832,65 @@
 romise;%0A
+import io.netty.util.internal.ThreadLocalRandom;%0A
 import i
@@ -924,16 +924,16 @@
 bleApi;%0A
-
 %0Aimport 
@@ -1111,58 +1111,8 @@
 ist;
-%0Aimport java.util.concurrent.atomic.AtomicInteger;
 %0A%0A/*
@@ -1590,69 +1590,8 @@
 ver;
-%0A    private final AtomicInteger index = new AtomicInteger();
 %0A%0A  
@@ -3029,34 +3029,20 @@
 get(
-index.getAndIncrement() %25 
+randomIndex(
 numA
@@ -3051,16 +3051,17 @@
 resses))
+)
 ;%0A      
@@ -4168,30 +4168,40 @@
 lt, 
-index.getAndIncrement(
+randomIndex(inetAddresses.size()
 ));%0A
@@ -4467,32 +4467,32 @@
 %7D%0A            %7D%0A
-
         %7D);%0A    
@@ -4492,11 +4492,163 @@
 );%0A    %7D
+%0A%0A    private static int randomIndex(int numAddresses) %7B%0A        return numAddresses == 1 ? 0 : ThreadLocalRandom.current().nextInt(numAddresses);%0A    %7D
 %0A%7D%0A

Revert counter optimization in RoundRobin until better implementation found