var sys = require('util');
var stomp = require('stomp');

/*
 * Test simple send and recieve use case from memtop-a.
 */

var stomp_args = {
    port: 61613,
    host: process.argv[2] ? process.argv[2] : 'localhost',
    debug: false,
    login: "smokey",
    passcode: "passcode",
};

var testMessage =  "Testing\n" + process.env.TEST_DATE + "\n123";

var errorHandler = function(error_frame) {
    console.log("error");
    console.log("headers: " + sys.inspect(error_frame.headers));
    console.log("body: " + error_frame.body);
    publisher.disconnect();
    subscriber.disconnect();
};


var subscriber = new stomp.Stomp(stomp_args);
var publisher = new stomp.Stomp(stomp_args);

// SUBSCRIBER - start

subscriber.connect();

subscriber.on("connected", function() {
    subscriber.subscribe({
        destination: "memtop-a",
        id : "1",
        ack: "client",
        receipt: "sub" 
    });
});

subscriber.on("receipt", function(id) {
    if (id === "sub") {
        subscriber.subscribed = true;
    }
    else if (id === "unsub") {
        subscriber.disconnect();
    }
    else console.error("unexpected receipt");
});

subscriber.on("message", function(message) {
    if (testMessage !== "" + message.body) {
        console.error("message different");
        console.error("send:" + testMessage);
        console.error("recv:" + message.body);
    }
    subscriber.ack(message.headers["message-id"]);
    subscriber.unsubscribe({
        destination: "memtop-a",
        id : "1",
        receipt: "unsub" 
    });
});

subscriber.on("error", errorHandler);

// SUBSCRIBER - end

// PUBLISHER - start

var publisher = new stomp.Stomp(stomp_args);
publisher.connect();

publisher.on("connected", function() {
    if (subscriber.subscribed ) {
        publisher.send({
            "destination" : "memtop-a",
            "body" : testMessage,
            "receipt" : "send"
        });
    }
    else {
        setTimeout(function() {
            publisher.send({
                "destination" : "memtop-a",
                "body" : testMessage,
                "receipt" : "send"
            });
        }, 100);
    }
});

publisher.on("receipt", function(id) {
    if (id === "send") {
        publisher.disconnect();
    }
    else console.error("unexpected receipt");
});

publisher.on("error", errorHandler);

// PUBLISHER - end

process.on("SIGINT", function() {
    publisher.disconnect();
    subscriber.disconnect();
    process.exit(0);
});