/**
 * 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.group;

import junit.framework.TestCase;
import org.apache.activeblaze.BlazeChannel;
import org.apache.activeblaze.BlazeMessage;
import org.apache.activeblaze.BlazeMessageListener;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Test BlazeGroupChannel
 */
public class BlazeGroupChannelTest extends TestCase {
    /**
     * Test method for
     * {@link org.apache.activeblaze.group.BlazeGroupChannel#send(org.apache.activeblaze.group.Member, org.apache.activeblaze.BlazeMessage)}
     * .
     */
    public void testSendMemberBlazeMessage() throws Exception {
        final int number = 5;
        final AtomicInteger count = new AtomicInteger();
        List<BlazeGroupChannel> channels = new ArrayList<BlazeGroupChannel>();
        BlazeGroupChannelFactory factory = new BlazeGroupChannelFactory();
        for (int i = 0; i < number; i++) {
            BlazeGroupChannel channel = factory.createGroupChannel("test" + i);
            channel.addToGroup("test");
            channel.start();
            channels.add(channel);
            channel.setInboxListener(new BlazeMessageListener() {
                public void onMessage(BlazeMessage message) {
                    synchronized (count) {
                        synchronized (count) {
                            count.incrementAndGet();
                            count.notifyAll();
                        }
                    }
                }
            });
        }
        channels.get(0).getAndWaitForMemberByName(channels.get(number - 1).getName(), 2000);
        BlazeMessage msg = new BlazeMessage();
        msg.setStringValue("test", "hello");
        channels.get(0).send(channels.get(1).getLocalMember(), msg);
        synchronized (count) {
            if (count.get() == 0) {
                count.wait(5000);
            }
        }
        // wait a while to check that only one got it
        Thread.sleep(2000);
        assertEquals(1, count.get());
        for (BlazeGroupChannel channel : channels) {
            channel.shutDown();
        }
    }

    /**
     * Test method for
     * {@link org.apache.activeblaze.group.BlazeGroupChannel#sendRequest(org.apache.activeblaze.group.Member, org.apache.activeblaze.BlazeMessage)}
     * .
     */
    public void testSendRequestMemberBlazeMessage() throws Exception {
        final int number = 100;
        final List<BlazeMessage> requests = new ArrayList<BlazeMessage>();
        final List<BlazeMessage> replies = new ArrayList<BlazeMessage>();
        for (int i = 0; i < number; i++) {
            requests.add(new BlazeMessage("request" + i));
            replies.add(new BlazeMessage("reply" + i));
        }
        BlazeGroupChannelFactory factory = new BlazeGroupChannelFactory();
        final BlazeGroupChannel request = factory.createGroupChannel("request");
        final BlazeGroupChannel reply = factory.createGroupChannel("reply");
        request.addToGroup("test");
        reply.addToGroup("test");
        request.start();
        reply.start();
        reply.setInboxListener(new BlazeMessageListener() {
            public void onMessage(BlazeMessage message) {
                if (!replies.isEmpty()) {
                    BlazeMessage replyMsg = replies.remove(0);
                    try {
                        Member to = reply.getMemberById(message.getFromId());
                        reply.sendReply(to, replyMsg, message.getMessageId());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        Thread.sleep(100);
        Member target = request.getMemberByName("reply");
        for (int i = 0; i < requests.size(); i++) {
            BlazeMessage requestMsg = requests.get(i);
            BlazeMessage replyMsg = request.sendRequest(target, requestMsg);
            assertNotNull(replyMsg);
        }
        assertTrue(replies.isEmpty());
        request.shutDown();
        reply.shutDown();
    }

    public void testSendRequestString() throws Exception {
        String destination = "/test/foo";
        final int number = 10;
        final List<BlazeMessage> requests = new ArrayList<BlazeMessage>();
        final List<BlazeMessage> replies = new ArrayList<BlazeMessage>();
        for (int i = 0; i < number; i++) {
            requests.add(new BlazeMessage("request" + i));
            replies.add(new BlazeMessage("reply" + i));
        }
        BlazeGroupChannelFactory factory = new BlazeGroupChannelFactory();
        final BlazeGroupChannel request = factory.createGroupChannel("request");
        final BlazeGroupChannel reply = factory.createGroupChannel("reply");
        reply.addBlazeQueueMessageListener(destination, new BlazeMessageListener() {
            public void onMessage(BlazeMessage message) {
                if (!replies.isEmpty()) {
                    BlazeMessage replyMsg = replies.remove(0);
                    try {
                        Member to = reply.getMemberById(message.getFromId());
                        reply.sendReply(to, replyMsg, message.getMessageId());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        request.addToGroup("test");
        reply.addToGroup("test");
        request.start();
        reply.start();
        Member result = request.getAndWaitForMemberByName("reply", 10000);
        assertNotNull(result);
        for (int i = 0; i < requests.size(); i++) {
            BlazeMessage requestMsg = requests.get(i);
            BlazeMessage replyMsg = request.sendRequest(destination, requestMsg, 1000);
            assertNotNull(replyMsg);
        }
        assertTrue(replies.isEmpty());
        request.shutDown();
        reply.shutDown();
    }

    /**
     * Test method for
     * {@link org.apache.activeblaze.group.BlazeGroupChannel#send(java.lang.String, org.apache.activeblaze.BlazeMessage)}
     * .
     */
    public void testSendStringBlazeMessage() throws Exception {
        final int number = 2;
        String destination = "test.foo";
        final AtomicInteger count = new AtomicInteger();
        List<BlazeGroupChannel> channels = new ArrayList<BlazeGroupChannel>();
        BlazeGroupChannelFactory factory = new BlazeGroupChannelFactory();
        for (int i = 0; i < number; i++) {
            BlazeGroupChannel channel = factory.createGroupChannel("test" + i);
            channel.addToGroup("test");
            channel.start();
            channels.add(channel);
            channel.addBlazeQueueMessageListener(destination, new BlazeMessageListener() {
                public void onMessage(BlazeMessage message) {
                    synchronized (count) {
                        synchronized (count) {
                            count.incrementAndGet();
                            count.notifyAll();
                        }
                    }
                }
            });
        }
        Thread.sleep(2000);
        BlazeMessage msg = new BlazeMessage("hello");
        BlazeGroupChannel channel = channels.get(0);
        channel.send(destination, msg);
        synchronized (count) {
            if (count.get() == 0) {
                count.wait(5000);
            }
        }
        // wait a while to check that only one got it
        Thread.sleep(2000);
        assertEquals(1, count.get());
        for (BlazeChannel c : channels) {
            c.shutDown();
        }
    }
}
