/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF 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.apache.activeblaze.cluster;

import junit.framework.TestCase;
import org.apache.activeblaze.group.Member;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Tests for ClusterState
 */
public class ClusterStateTest extends TestCase {
    protected BlazeClusterGroupChannel channel1;
    protected BlazeClusterGroupChannel channel2;

    public void testAddAndRemove() throws Exception {
        ClusterState state1 = this.channel1.getState();
        final int number = 1000;
        final CountDownLatch addLatch = new CountDownLatch(number);
        final CountDownLatch removeLatch = new CountDownLatch(number);
        state1.addClusterStateChangedListener(new DefaultClusterStateListener() {
            public void mapInsert(Member owner, String Key, Object Value) {
                addLatch.countDown();
            }

            public void mapRemove(Member owner, String key, Object value, boolean expired) {
                removeLatch.countDown();
            }
        });
        this.channel1.start();
        this.channel2.getConfiguration().setMinimumGroupSize(2);
        ClusterState state2 = this.channel2.getState();
        this.channel2.start();
        this.channel2.waitForElection(0);
        validateCluster();
        for (int i = 0; i < number; i++) {
            state2.put("" + i, "test" + i);
        }
        addLatch.await(5, TimeUnit.SECONDS);
        assertEquals(0, addLatch.getCount());
        for (int i = 0; i < number; i++) {
            state2.remove("" + i);
        }
        removeLatch.await(5, TimeUnit.SECONDS);
        assertEquals(0, removeLatch.getCount());
        assertTrue(state1.isEmpty());
    }

    public void testAddClusterStateChangedListener() throws Exception {
        final AtomicBoolean called1 = new AtomicBoolean();
        final AtomicBoolean called2 = new AtomicBoolean();
        ClusterState state1 = this.channel1.getState();
        state1.addClusterStateChangedListener(new DefaultClusterStateListener() {
            public void mapInsert(Member owner, String Key, Object Value) {
                synchronized (called1) {
                    called1.set(true);
                    called1.notifyAll();
                }
            }
        });
        this.channel1.start();
        ClusterState state2 = this.channel2.getState();
        state2.addClusterStateChangedListener(new DefaultClusterStateListener() {
            public void mapInsert(Member owner, String Key, Object Value) {
                synchronized (called2) {
                    called2.set(true);
                    called2.notifyAll();
                }
            }
        });
        this.channel2.getConfiguration().setMinimumGroupSize(2);
        this.channel2.start();
        this.channel2.waitForElection(0);
        validateCluster();
        state1.put("test", "blob");
        synchronized (called1) {
            if (!called1.get()) {
                called1.wait(5000);
            }
        }
        synchronized (called2) {
            if (!called2.get()) {
                called2.wait(5000);
            }
        }
        assertTrue(called1.get());
        assertTrue(called2.get());
    }

    public void testGetImplicitWriteLock() throws Exception {
        ClusterState state1 = this.channel1.getState();
        final AtomicBoolean called = new AtomicBoolean();
        this.channel1.start();
        ClusterState state2 = this.channel2.getState();
        state2.setAlwaysLock(true);
        this.channel2.getConfiguration().setMinimumGroupSize(2);
        this.channel2.start();
        this.channel2.waitForElection(0);
        validateCluster();
        state2.put("test", "foo");
        try {
            state1.put("test", "bah");
            fail("Should have thrown an exception!");
        } catch (ClusterUpdateException e) {
        }
    }

    public void testExpireImplicitWriteLock() throws Exception {
        ClusterState state1 = this.channel1.getState();
        final AtomicBoolean called = new AtomicBoolean();
        this.channel1.start();
        ClusterState state2 = this.channel2.getState();
        state2.setAlwaysLock(true);
        state2.setLockTimeToLive(1000);
        this.channel2.getConfiguration().setMinimumGroupSize(2);
        this.channel2.start();
        this.channel2.waitForElection(0);
        state2.put("test", "foo");

        try {

            state1.put("test", "bah");
            fail("Should have thrown an exception!");
        } catch (ClusterUpdateException e) {

        }
        Thread.sleep(2000);
        state1.put("test", "bah");
    }

    public void testExpireImplicitLockOnExit() throws Exception {

        ClusterState state1 = this.channel1.getState();
        this.channel1.start();
        ClusterState state2 = this.channel2.getState();
        state2.setAlwaysLock(true);
        //state2.setLockTimeToLive(1000);
        this.channel2.getConfiguration().setMinimumGroupSize(2);


        this.channel2.start();
        this.channel2.waitForElection(0);
        validateCluster();
        state2.put("test", "foo");
        try {
            state1.put("test", "bah");
            fail("Should have thrown an exception!");
        } catch (ClusterUpdateException e) {
        }
        this.channel2.shutDown();
        this.channel1.getConfiguration().setMinimumGroupSize(1);
        Thread.sleep(2000);
        state1.put("test", "bah");
    }

    public void testGetExplicitWriteLock() throws Exception {
        ClusterState state1 = this.channel1.getState();
        state1.setAlwaysLock(true);
        this.channel1.start();
        ClusterState state2 = this.channel2.getState();
        state2.setAlwaysLock(true);
        this.channel2.getConfiguration().setMinimumGroupSize(2);
        this.channel2.start();
        this.channel2.waitForElection(0);
        validateCluster();
        state2.put("test", "foo");
        state2.lock("test");
        try {
            state1.put("test", "bah");
            fail("Should have thrown an exception!");
        } catch (ClusterUpdateException e) {
        }
        state2.unlock("test");
        state1.lock("test");
        try {
            state2.lock("test");
            fail("Should have thrown an exception!");
        } catch (ClusterUpdateException e) {
        }
    }

    public void testClear() throws Exception {
        ClusterState state1 = this.channel1.getState();
        final AtomicBoolean called = new AtomicBoolean();
        state1.addClusterStateChangedListener(new DefaultClusterStateListener() {
            public void mapInsert(Member owner, String Key, Object Value) {
                synchronized (called) {
                    called.set(true);
                    called.notifyAll();
                }
            }

            public void mapRemove(Member owner, String key, Object value, boolean expired) {
                synchronized (called) {
                    called.set(true);
                    called.notifyAll();
                }
            }
        });
        this.channel1.start();
        ClusterState state2 = this.channel2.getState();
        this.channel2.getConfiguration().setMinimumGroupSize(2);
        this.channel2.start();
        this.channel2.waitForElection(5000);
        validateCluster();
        state2.put("test", "foo");
        synchronized (called) {
            if (!called.get()) {
                called.wait(5000);
            }
        }
        assertTrue(called.get());
        called.set(false);
        assertTrue(state1.isEmpty() == false);
        state2.clear();
        synchronized (called) {
            if (!called.get()) {
                called.wait(5000);
            }
        }
        assertTrue(state1.isEmpty());
    }

    public void testMapUpdatedOnStart() throws Exception {
        ClusterState state1 = this.channel1.getState();
        final AtomicBoolean called = new AtomicBoolean();
        this.channel1.getConfiguration().setMinimumGroupSize(1);
        this.channel1.start();
        state1.put("test", "foo");
        ClusterState state2 = this.channel2.getState();
        state2.addClusterStateChangedListener(new DefaultClusterStateListener() {
            public void mapInsert(Member owner, String Key, Object Value) {
                synchronized (called) {
                    called.set(true);
                    called.notifyAll();
                }
            }
        });
        this.channel2.getConfiguration().setMinimumGroupSize(2);
        this.channel2.start();
        this.channel2.waitForElection(0);
        validateCluster();
        synchronized (called) {
            if (!called.get()) {
                called.wait(5000);
            }
        }
        assertTrue(called.get());
        called.set(false);
        assertTrue(state2.containsKey("test"));
        assertTrue(state2.containsValue("foo"));
    }

    public void testContainsKey() throws Exception {
        ClusterState state1 = this.channel1.getState();
        final AtomicBoolean called = new AtomicBoolean();
        state1.addClusterStateChangedListener(new DefaultClusterStateListener() {
            public void mapInsert(Member owner, String Key, Object Value) {
                synchronized (called) {
                    called.set(true);
                    called.notifyAll();
                }
            }
        });
        this.channel1.start();
        ClusterState state2 = this.channel2.getState();
        this.channel2.start();
        this.channel2.waitForElection(0);
        validateCluster();
        state2.put("test", "foo");
        synchronized (called) {
            if (!called.get()) {
                called.wait(5000);
            }
        }
        assertTrue(called.get());
        called.set(false);
        assertTrue(state1.containsKey("test"));
    }

    public void testContainsValue() throws Exception {
        ClusterState state1 = this.channel1.getState();
        final AtomicBoolean called = new AtomicBoolean();
        state1.addClusterStateChangedListener(new DefaultClusterStateListener() {
            public void mapInsert(Member owner, String Key, Object Value) {
                synchronized (called) {
                    called.set(true);
                    called.notifyAll();
                }
            }
        });
        this.channel1.start();
        ClusterState state2 = this.channel2.getState();
        this.channel2.getConfiguration().setMinimumGroupSize(2);
        this.channel2.start();
        this.channel2.waitForElection(0);
        validateCluster();
        state2.put("test", "foo");
        synchronized (called) {
            if (!called.get()) {
                called.wait(5000);
            }
        }
        assertTrue(called.get());
        called.set(false);
        assertTrue(state1.containsValue("foo"));
    }

    public void testGet() throws Exception {
        ClusterState state1 = this.channel1.getState();
        final AtomicBoolean called = new AtomicBoolean();
        state1.addClusterStateChangedListener(new DefaultClusterStateListener() {
            public void mapInsert(Member owner, String Key, Object Value) {
                synchronized (called) {
                    called.set(true);
                    called.notifyAll();
                }
            }
        });
        this.channel1.start();
        ClusterState state2 = this.channel2.getState();
        this.channel2.getConfiguration().setMinimumGroupSize(2);
        this.channel2.start();
        this.channel2.waitForElection(0);
        validateCluster();
        state2.put("test", "foo");
        synchronized (called) {
            if (!called.get()) {
                called.wait(5000);
            }
        }
        assertTrue(called.get());
        assertTrue(state1.get("test").equals("foo"));
    }

    public void testPut() throws Exception {
        ClusterState state1 = this.channel1.getState();
        this.channel1.start();
        ClusterState state2 = this.channel2.getState();
        this.channel2.getConfiguration().setMinimumGroupSize(2);
        this.channel2.start();
        this.channel2.waitForElection(0);
        validateCluster();
        Object value = state1.put("foo", "blob");
        assertNull(value);
        value = state1.put("foo", "blah");
        assertEquals("blob", value);
    }

    public void testRemove() throws Exception {
        ClusterState state1 = this.channel1.getState();
        final AtomicBoolean called = new AtomicBoolean();
        state1.addClusterStateChangedListener(new DefaultClusterStateListener() {
            public void mapInsert(Member owner, String Key, Object Value) {
                synchronized (called) {
                    called.set(true);
                    called.notifyAll();
                }
            }

            public void mapRemove(Member owner, String key, Object value, boolean expired) {
                synchronized (called) {
                    called.set(true);
                    called.notifyAll();
                }
            }
        });
        this.channel1.start();
        ClusterState state2 = this.channel2.getState();
        this.channel2.getConfiguration().setMinimumGroupSize(2);
        this.channel2.start();
        this.channel2.waitForElection(0);
        validateCluster();
        state2.put("test", "foo");
        synchronized (called) {
            if (!called.get()) {
                called.wait(5000);
            }
        }
        assertTrue(called.get());
        called.set(false);
        assertTrue(state1.isEmpty() == false);
        state2.remove("test");
        synchronized (called) {
            if (!called.get()) {
                called.wait(5000);
            }
        }
        assertTrue(state1.isEmpty());
    }

    public void testExpire() throws Exception {
        final AtomicBoolean called1 = new AtomicBoolean();
        final AtomicBoolean called2 = new AtomicBoolean();
        ClusterState state1 = this.channel1.getState();
        state1.setTimeToLive(10);
        state1.addClusterStateChangedListener(new DefaultClusterStateListener() {
            public void mapRemove(Member owner, String key, Object value, boolean expired) {
                synchronized (called1) {
                    called1.set(expired);
                    called1.notifyAll();
                }
            }
        });
        this.channel1.start();
        ClusterState state2 = this.channel2.getState();
        state2.addClusterStateChangedListener(new DefaultClusterStateListener() {
            public void mapRemove(Member owner, String key, Object value, boolean expired) {
                synchronized (called2) {
                    called2.set(expired);
                    called2.notifyAll();
                }
            }
        });
        this.channel2.getConfiguration().setMinimumGroupSize(2);
        this.channel2.start();
        this.channel2.waitForElection(0);
        validateCluster();
        state1.put("test", "blob");
        synchronized (called1) {
            if (!called1.get()) {
                called1.wait(5000);
            }
        }
        synchronized (called2) {
            if (!called2.get()) {
                called2.wait(5000);
            }
        }
        assertTrue(called1.get());
        assertTrue(called2.get());
    }

    protected void setUp() throws Exception {
        BlazeClusterGroupChannelFactory factory = new BlazeClusterGroupChannelFactory();
        this.channel1 = factory.createChannel("channel1");
        this.channel2 = factory.createChannel("channel2");
        this.channel1.addToGroup("test");
        this.channel2.addToGroup("test");
        this.channel1.getConfiguration().setMinimumGroupSize(2);
        this.channel2.getConfiguration().setMinimumGroupSize(2);
        super.setUp();
    }

    protected void tearDown() throws Exception {
        super.tearDown();
        this.channel1.shutDown();
        this.channel2.shutDown();
    }

    protected void validateCluster() throws Exception {
        assertFalse(this.channel2.isMaster() && this.channel1.isMaster());
        assertTrue(this.channel2.isMaster() || this.channel1.isMaster());
    }
}
