"use-strict"

var lexer = require("Lexer");
var testData = require("TestData");

var publisher = null;

var httpSendLandingPage = function(response) {
  var body = '<html><body>Providence WCTP Gateway</body></html>'
  response.setContentType("text/html");
  response.send(body);
}

httpSendOk = function(response) {
  var body = '<?xml version=\"1.0\"?>' +
    '<!DOCTYPE wctp-Operation SYSTEM \"http://dtd.wctp.org/wctp-dtd-v1r1.dtd\">' +
    '<wctp-Operation wctpVersion=\"wctp-dtd-v1r1\" wctpToken=\"11AA\">' +
    '<wctp-Confirmation>' +
    '<wctp-Success' +
    ' successCode=\"200\"' +
    ' successText=\"Message acknowledged\">' +
    'Your message is being processed' +
    '</wctp-Success>' +
    '</wctp-Confirmation>' +
    '</wctp-Operation>';
  response.setContentType("text/xml");
  response.send(body);
}

var httpRequestHandler = function(request, response) {
    console.log(request.clientAddress);
    
    var contentType = request.getContentType();
    if (contentType) {
      contentType = contentType.toLowerCase();
      if (contentType == "text/xml" || contentType == "application/xml") {
        var body = request.getBody();
        if (body.length > 0) {
          var wctpData = utils.bufferToString(body);
          if (wctpData.indexOf("wctp") != -1) {
            wctpData = utils.stringReplace(xmlData, "wctp-", "");
            log_info(wctpData);
            if (publisher) {
                var requestObject = lexer.finalize(request.clientAddress, wctpData);
                if (requestObject) {
                  console.log("Publishing Event " + requestObject);
                  publisher.publish(requestObject);
                }
            }
            httpSendOk(response);
            return;
          }
        }
      }
    } else if (request.uri = "/test"){
        var wctpData = testData.getRandomMessage();
        if (publisher) {
            var requestObject = lexer.finalize(request.clientAddress, wctpData);
            console.log("Publishing Event " + requestObject);
            publisher.publish(requestObject);
        }
        httpSendOk(response);
    } else {
      httpSendLandingPage(response);
      return;
    }
}

exports.initialize = function(http, config, pub) {
    publisher = pub;
    exports.httpServer = http.createServer(httpRequestHandler, config.enableSSL);
    if (exports.httpServer) {
        var port = (config.enableSSL ? config.httpsPort : config.httpPort);
        exports.httpServer.listen(port, function(err) {
        if (err) {
            console.log('Something bad happened', err);
            system.exit(-1);
        }
        console.log("Server is listening on " + port);
      });
    }
}

