var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var request = require('request');
var events = require('events');
var fh = require('fh-mbaas-api');
var _ = require('underscore');

var fuseRoute = function() {
  var fuse = new express.Router();
  fuse.use(cors());
  fuse.use(bodyParser());
 
  fuse.post('/', function(req, res) {
    console.log(new Date(), 'In fuse route POST / req.body=', req.body);
    return submitToFuse(req.body, function(error, response, body){
      return res.send(body);  
    });
  });
 
  return fuse;
};

var submitToFuse = function(submission, cb){
  var data = transform(submission);
  var url = process.env.FUSE_URL || 'http://85.190.180.161:8182/cxf/redhat/forum/register';
  var options = { "url" : url, "body": data, "json": true};
  request.post(options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log("Well done!") // Show the HTML
    }
    cb(error, response, body);
  });
};

var mapping = {
  "FFIRSTNAME" : "name",
  "FLASTNAME" : "lastName",
  "FEMAIL" : "email",
  "FPICTURE" : "picture",
  "FCOMPANY" : "companyName",
  "FTITLE" : "jobTitle"
};

var transform = function(submission) {
  var map = { "register" : { register : {} } };
  _.each(submission.submission.formFields, function(item){
    //console.log(JSON.stringify(item));
    map.register[mapping[item.fieldId.fieldCode]] = item.fieldValues[0];
  });
  console.log(JSON.stringify(map));
  return { "register" : map };
}

var submissionEventListener = new events.EventEmitter();

submissionEventListener.on('submissionComplete', function(submission){
  console.log('New submission received: ');
  //console.log(submission);
  return submitToFuse(submission, function(error, response, body){
      console.log('Received response from Fuse in event handler: ' + response.statusCode);
      console.log(body);
  });
});

fh.forms.registerListener(submissionEventListener, function(err){});
 
module.exports = fuseRoute;
@@ -1190,16 +1190,34 @@
 obTitle%22
+,%0A  %22FWEB%22 : %22web%22
 %0A%7D;%0A%0Avar
@@ -1284,22 +1284,8 @@
  : %7B
- register : %7B%7D
  %7D %7D
@@ -1513,29 +1513,12 @@
 turn
- %7B %22register%22 :
  map
- %7D
 ;%0A%7D%0A

update file /lib/fuse.js