var Pusher  = require('pusher'),
    os      = require('os'),
    express = require('express'),
    app     = express(),
    ch      = 'stats';

var pusher = new Pusher({
  appId: process.env.PUSHER_APP_ID,
  key: process.env.PUSHER_KEY,
  secret: process.env.PUSHER_SECRET
});

var pushStatistics = function(cb) {
  // Gather stats
  var load    = os.loadavg(),
      totmem  = os.totalmem(),
      freemem = os.freemem();

  pusher.trigger(ch, 'stats', {
    precentfreemem: (freemem/totmem).toFixed(3),
    load5: load[1].toFixed(3),
    node: os.hostname()
  });
  cb();
}

var statTimeout,
    setPushStatsTimer = function() {
      pushStatistics(function() {
        statTimeout = setTimeout(setPushStatsTimer, 5 * 1000);
      });
    }

app.get('/start', function(req, res) {
  setPushStatsTimer();  
  res.send('ok');
})

app.get('/stop', function(req, res) {
  clearTimeout(statTimeout);
  res.send('ok');
})

app.listen(process.env.PORT || 3000)