/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch 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 org.elasticsearch.client.transport;

import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.transport.MockTransportClient;
import org.elasticsearch.transport.TransportService;
import org.hamcrest.Matchers;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collector;
import java.util.stream.Collectors;

public class NodeDisconnectIT  extends ESIntegTestCase {

    public void testNotifyOnDisconnect() throws IOException {
        internalCluster().ensureAtLeastNumDataNodes(2);

        final Set<DiscoveryNode> disconnectedNodes = Collections.synchronizedSet(new HashSet<>());
        try (TransportClient client = new MockTransportClient(Settings.builder()
            .put("cluster.name", internalCluster().getClusterName()).build(), Collections.emptySet(), (n, e) -> disconnectedNodes.add(n))) {
            for (TransportService service : internalCluster().getInstances(TransportService.class)) {
                client.addTransportAddress(service.boundAddress().publishAddress());
            }
            internalCluster().stopRandomDataNode();
            for (int i = 0; i < 20; i++) { // fire up requests such that we hit the node and pass it to the listener
                client.admin().cluster().prepareState().get();
            }
            assertEquals(1, disconnectedNodes.size());
        }
        assertEquals(1, disconnectedNodes.size());
    }

    public void testNotifyOnDisconnectInSniffer() throws IOException {
        internalCluster().ensureAtLeastNumDataNodes(2);

        final Set<DiscoveryNode> disconnectedNodes = Collections.synchronizedSet(new HashSet<>());
        try (TransportClient client = new MockTransportClient(Settings.builder()
            .put("cluster.name", internalCluster().getClusterName()).build(), Collections.emptySet(), (n, e) -> disconnectedNodes.add(n))) {
            int numNodes = 0;
            for (TransportService service : internalCluster().getInstances(TransportService.class)) {
                numNodes++;
                client.addTransportAddress(service.boundAddress().publishAddress());
            }
            Set<TransportAddress> discoveryNodes = client.connectedNodes().stream().map(n -> n.getAddress()).collect(Collectors.toSet());
            assertEquals(numNodes, discoveryNodes.size());
            assertEquals(0, disconnectedNodes.size());
            internalCluster().stopRandomDataNode();
            client.getNodesService().doSample();
            assertEquals(1, disconnectedNodes.size());
            assertTrue(discoveryNodes.contains(disconnectedNodes.stream().findAny().get().getAddress()));
        }
        assertEquals(1, disconnectedNodes.size());
    }
}

@@ -1150,38 +1150,8 @@
 ice;
-%0Aimport org.hamcrest.Matchers;
 %0A%0Aim
@@ -1236,31 +1236,8 @@
 et;%0A
-import java.util.List;%0A
 impo
@@ -1287,25 +1287,27 @@
 ollector
-;
+s;%0A
 %0Aimport 
 java.uti
@@ -1302,35 +1302,105 @@
 ort 
-java.util.stream.Collectors
+static org.elasticsearch.client.transport.TransportClient.CLIENT_TRANSPORT_NODES_SAMPLER_INTERVAL
 ;%0A%0Ap
@@ -1507,32 +1507,54 @@
 rows IOException
+, InterruptedException
  %7B%0A        inter
@@ -1841,33 +1841,170 @@
 usterName())
-.build(),
+%0A            .put(CLIENT_TRANSPORT_NODES_SAMPLER_INTERVAL.getKey(), %221h%22) // disable sniffing for better control%0A            .build(),%0A           
  Collections
@@ -2286,34 +2286,37 @@
 uster().stop
-RandomData
+CurrentMaster
 Node();%0A    

disable sampling in testNotifyOnDisconnect