// Copyright 2011, 2012 Tony Garnock-Jones <tonygarnockjones@gmail.com>.
//
// This file is part of Hop.
//
// Hop is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Hop is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
// License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Hop.  If not, see <http://www.gnu.org/licenses/>.
//
package hop;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;

/**
 */
public class TestScale {
    static AtomicLong counter = new AtomicLong();

    public static void main(final String[] args) {
        try {
            final String hostname = args[0];
            int count = Integer.parseInt(args[1]);
            System.out.println("Hostname: " + hostname);
            for (int i = 0; i < count; i++) {
                new Thread(new Runnable() { public void run() {
                    try {
                        runConnection(hostname);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } }).start();
                Thread.sleep(100);
            }
            while (true) {
                long startTime = System.currentTimeMillis();
                long startCount = counter.longValue();
                Thread.sleep(1000);
                long now = System.currentTimeMillis();
                long countNow = counter.longValue();
                report(startTime, startCount, now, countNow);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void report(long t0, long c0, long t1, long c1) {
        double dc = c1 - c0;
        double dt = (t1 - t0) / 1000.0;
        double rate = dc / dt;
        System.out.println(dc + " messages in " + dt + "s = " + rate + " Hz");
    }

    public static void runConnection(String hostname) throws IOException, InterruptedException {
        NodeContainer nc = new NodeContainer();
        String qName = nc.getName() + "q";
        System.out.println("Queue: " + qName);

        Relay r = new Relay(nc, hostname);
        ServerApi api = new ServerApi(nc, r.getRemoteName());

        api.createQueue(qName);
        Subscription sub = api.subscribe(qName, null);
        while (true) {
            Object in = "a";
            api.post(qName, "", in, null);
            api.flush();
            Object out = sub.getQueue().take();
            assert in.equals(out);
            counter.incrementAndGet();
        }
    }
}
