var express = require('express');
var childProcess = require('child_process');
var middleware = require('./config/initializers/middleware.js');
var router = require('./config/routes.js');
var host = process.env.HOST;
var port = process.env.PORT || 4000;
var app = express();
var sequelize = require('./config/initializers/sequelize.js');
var nconf = require('./config/nconf.js');
var fs = require('fs');
var https = require('https');

middleware.configure(app);
router.route(app);

sequelize.sync().success(function(){
  var ssl = nconf.get('SSL');
  if (ssl == 'false') { 
    ssl = false 
  } else {
    var sslOptions = {
      key: fs.readFileSync('./certs/server.key'),
      cert: fs.readFileSync('./certs/server.crt')
    };
  }
  if (host && ssl) {
    https.createServer(sslOptions, app).listen(port, host);
  } else if (ssl) {
    https.createServer(sslOptions, app).listen(port);
  } else if (host) {
    app.listen(port, host);
  } else {
    app.listen(port);
  }
  
  var incomingPaymentsMonitor = childProcess.spawn("node", ["workers/listener.js"]);

  incomingPaymentsMonitor.stdout.on('data', function(data){
    console.log(data.toString());
  });

  incomingPaymentsMonitor.stderr.on('data', function(data){  
    console.log(data.toString());
  });

  setTimeout(function(){
    var outgoingPaymentsMonitor = childProcess.spawn("node", ["workers/outgoing_ripple_payments.js"]);
    outgoingPaymentsMonitor.stdout.on('data', function(data) {
      console.log(data.toString());
    });

    outgoingPaymentsMonitor.stderr.on('data', function(data) {
      console.log(data.toString());
    });
  },10000);

  console.log('Serving '+ (ssl ? 'HTTPS' : 'HTTP') +' on', (host || 'localhost')+":"+port);
})


@@ -1058,17 +1058,16 @@
 .js%22%5D);%0A
-%0A
   incomi
@@ -1075,32 +1075,37 @@
 gPaymentsMonitor
+%0A    
 .stdout.on('data
@@ -1123,16 +1123,18 @@
 (data)%7B%0A
+  
     cons
@@ -1161,20 +1161,20 @@
 g());%0A  
+  
 %7D)
-;%0A
 %0A  incom
@@ -1183,32 +1183,37 @@
 gPaymentsMonitor
+%0A    
 .stderr.on('data
@@ -1233,24 +1233,26 @@
 ata)%7B  %0A    
+  
 console.log(
@@ -1275,40 +1275,15 @@
 ;%0A  
+ 
+ 
 %7D);%0A%0A
-  setTimeout(function()%7B%0A  
   va
@@ -1379,18 +1379,16 @@
 .js%22%5D);%0A
-  
   outgoi
@@ -1436,34 +1436,32 @@
 ion(data) %7B%0A    
-  
 console.log(data
@@ -1474,27 +1474,23 @@
 ing());%0A
-  
   %7D);%0A%0A
-  
   outgoi
@@ -1542,26 +1542,24 @@
 data) %7B%0A    
-  
 console.log(
@@ -1582,25 +1582,203 @@
 ;%0A  
-  %7D);%0A  %7D,10000);
+%7D);%0A%0A  nconf.set('processes:server', process.pid);%0A  nconf.set('processes:incoming', incomingPaymentsMonitor.pid);%0A  nconf.set('processes:outgoing', outgoingPaymentsMonitor.pid);%0A  nconf.save();%0A
 %0A%0A  

Save process ids to nconf for lookup and termination.