"use-strict"
var rpc = require("json_rpc");
var http = require("http");

var config = require("Config");
var zmq = require("zmq");

if (config.notifierPIDFile && config.notifierPIDFile.length > 0) {
  if (!system.write_pid_file(config.notifierPIDFile, true)) {
    console.log("Unable to write PID file " + config.notifierPIDFile);
    system.exit(-1);
  }
}

var subscriber = new zmq.ZMQSocket(zmq.SUB);

if (!subscriber.connect(config.publisherAddress)) {
    console.log("Unable to connect to publisher address " + config.publisherAddress);
    system.exit(-1);
}

if (!subscriber.subscribe("")) {
    console.log("Unable to subscribe to publisher address " + config.publisherAddress);
    system.exit(-1);
}

if (config.pushNotificationUseTls) {
    http.ssl.registerClientContext(
      config.sslKey,
      function(){console.log("Password Verification")}, 
      config.sslCert,
      function(cert)
      {
        console.log("CLIENT", JSON.stringify(cert));
        return true;
      },
      config.caLocation,
      http.ssl.VERIFY_NONE
    );
}

var sender = new rpc.JsonRpcClient(new rpc.JsonRpcHttpClient(config.pushNotificationHost, config.pushNotificationPort, config.pushNotificationUseTls));


var validate_object = function(obj) {
  return !(!obj ||
         !obj.Operation ||
         !obj.Operation.SubmitRequest ||
         !obj.Operation.SubmitRequest.SubmitHeader ||
         !obj.Operation.SubmitRequest.SubmitHeader.Originator ||
         !obj.Operation.SubmitRequest.SubmitHeader.MessageControl ||
         !obj.Operation.SubmitRequest.SubmitHeader.Recipient ||
         !obj.Operation.SubmitRequest.Payload ||
         !obj.Operation.SubmitRequest.Payload.Alphanumeric);
 }

subscriber.start(function() {
    var msg = new Buffer(2048);
    subscriber.receive(msg);
    console.log(msg.toString());
    var obj = JSON.parse(msg.toString());
    if (validate_object(obj)) {
      sender.execute(config.pushNotificationUri, config.pushNotificationMethod, obj, function(response){
          console.log(response.toJSON(null, 2));
      });
    }
});


