/*
 * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
 *
 * 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 com.hazelcast.client.connection.nio;

import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.impl.HazelcastClientInstanceImpl;
import com.hazelcast.client.spi.properties.ClientProperty;
import com.hazelcast.client.test.ClientTestSupport;
import com.hazelcast.client.test.TestHazelcastFactory;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.LifecycleEvent;
import com.hazelcast.core.LifecycleListener;
import com.hazelcast.nio.Address;
import com.hazelcast.test.HazelcastParametersRunnerFactory;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.After;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.concurrent.CountDownLatch;

import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;

@RunWith(Parameterized.class)
@Parameterized.UseParametersRunnerFactory(HazelcastParametersRunnerFactory.class)
@Category({QuickTest.class, ParallelTest.class})
public class ConnectMemberListOrderTest extends ClientTestSupport {

    private TestHazelcastFactory factory = new TestHazelcastFactory();

    @Parameterized.Parameters(name = "shuffleMemberList == {0}")
    public static Collection<Object[]> params() {
        return asList(new Object[][]{{"false"}, {"true"}});
    }

    @Parameterized.Parameter
    public String shuffleMemberList;

    @After
    public void cleanup() {
        factory.shutdownAll();
    }

    @Test
    public void testPossibleMemberAddressesAfterDisconnection() throws Exception {
        HazelcastInstance instance = factory.newHazelcastInstance();
        ClientConfig config = new ClientConfig();
        config.setProperty(ClientProperty.SHUFFLE_MEMBER_LIST.getName(), shuffleMemberList);
        HazelcastInstance client = factory.newHazelcastClient(config);

        final CountDownLatch connectedBack = new CountDownLatch(1);
        client.getLifecycleService().addLifecycleListener(new LifecycleListener() {
            @Override
            public void stateChanged(LifecycleEvent event) {
                if (LifecycleEvent.LifecycleState.CLIENT_CONNECTED.equals(event.getState())) {
                    connectedBack.countDown();
                }
            }
        });

        factory.newHazelcastInstance();
        factory.newHazelcastInstance();

        makeSureConnectedToServers(client, 3);
        Address lastConnectedMemberAddress = new Address((InetSocketAddress) instance.getLocalEndpoint().getSocketAddress());
        instance.shutdown();

        assertOpenEventually(connectedBack);

        Collection<Address> possibleMemberAddresses = getPossibleMemberAddresses(client);

        //make sure last known member list is used. otherwise it returns 2
        assertEquals(3, possibleMemberAddresses.size());

        //make sure previous owner is not first one to tried in next owner connection selection
        assertNotEquals("possibleMemberAddresses : " + possibleMemberAddresses + ", lastConnectedMemberAddress "
                + lastConnectedMemberAddress, possibleMemberAddresses.iterator().next(), lastConnectedMemberAddress);
    }

    private Collection<Address> getPossibleMemberAddresses(HazelcastInstance client) {
        HazelcastClientInstanceImpl instanceImpl = getHazelcastClientInstanceImpl(client);
        ClientConnectionManagerImpl connectionManager = (ClientConnectionManagerImpl) instanceImpl.getConnectionManager();
        return connectionManager.getPossibleMemberAddresses();
    }

}

@@ -935,32 +935,76 @@
 zelcastFactory;%0A
+import com.hazelcast.config.ListenerConfig;%0A
 import com.hazel
@@ -2663,80 +2663,8 @@
 t);%0A
-        HazelcastInstance client = factory.newHazelcastClient(config);%0A%0A
     
@@ -2723,17 +2723,17 @@
 wnLatch(
-1
+2
 );%0A     
@@ -2740,56 +2740,44 @@
    c
-lient.getLifecycleService().addLifecycle
+onfig.addListenerConfig(new 
 Listener
 (new
@@ -2772,16 +2772,22 @@
 Listener
+Config
 (new Lif
@@ -3072,16 +3072,89 @@
       %7D)
+);%0A%0A        HazelcastInstance client = factory.newHazelcastClient(config)
 ;%0A%0A     

test fix possibleMemberAddressesAfterDisconnection