var forever = require(__dirname+'/node_modules/forever-monitor');
var fs = require(__dirname+'/node_modules/fs-extra');

var getDateTimeString = () => {
  var date = new Date();
  var hour = date.getHours();
  hour = (hour < 10 ? "0" : "") + hour;
  var min  = date.getMinutes();
  min = (min < 10 ? "0" : "") + min;
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  month = (month < 10 ? "0" : "") + month;
  var day  = date.getDate();
  day = (day < 10 ? "0" : "") + day;
  return year + "-" + month + "-" + day + "_" + hour + "-" + min;
};
var log_forever = __dirname+'/log/forever_'+getDateTimeString()+'.log';
var log_bot = __dirname+'/log/bot_'+getDateTimeString()+'.log';
var err_bot = __dirname+'/log/err_'+getDateTimeString()+'.log';
var putlog = (msg) => {
  fs.appendFileSync(log_forever, msg, 'utf8');
};

var child = new (forever.Monitor)(__dirname+'/src/main.js', {
  max: 1,
  silent: false,
  cwd: __dirname,
  args: [],
  spinSleepTime: 5000,
  watch: true,
  watchIgnoreDotFiles: true,
  watchIgnorePatterns: [
    '*.log', 'b/*', 't/*', 'node_modules/* ./.*'
  ],
  watchDirectory: __dirname,
  outFile: log_bot,
  errFile: err_bot
});

child.on('watch:restart', (info) => {
  putlog('Restaring bot because ' + info.stat + ' changed\n');
});
child.on('restart', () => {
  putlog('restarting bot for ' + child.times + ' time\n');
});
child.on('start', () => {
  putlog('starting bot\n');
});
child.on('exit:code', (code) => {
  putlog('detected bot exited with code ' + code + '\n');
  child.restart();
});
child.start();
