// 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;

/**
 */
public class TestPingPong {
    public static void main(final String[] args) {
        try {
            new Thread(new Runnable() { public void run() {
                try {
                    run1(args[0]);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } }).start();
            run2(args[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void run1(String hostname) throws IOException, InterruptedException {
        NodeContainer nc = new NodeContainer();

        System.out.println("Hostname: " + hostname);
        System.out.println("Container: " + nc.getName());

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

        api.createQueue("req");
        Subscription sub = api.subscribe("req", null);
        while (true) {
            Object x = sub.getQueue().take();
            //System.out.println("Message: " + x);
            api.post("rep", "reply", SexpList.with("ok").and(x), null);
            api.flush();
        }
    }

    public static void run2(String hostname) throws IOException, InterruptedException {
        NodeContainer nc = new NodeContainer();

        System.out.println("Hostname: " + hostname);
        System.out.println("Container: " + nc.getName());

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

        api.createQueue("req");
        api.createQueue("rep");
        Subscription sub = api.subscribe("rep", null);
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            api.post("req", "request", Integer.toString(i), null);
            api.flush();
            sub.getQueue().take();
            int j = i + 1;
            if ((j % 100) == 0) {
                long now = System.currentTimeMillis();
                double delta = (now - startTime) / 1000.0;
                System.out.println("Message " + j + ": " + (j / delta) + " Hz");
            }
        }
    }
}
