var fs = require('fs');
var path = require('path');
var utils = require('utils');

function logUncaughtError(err) {
  var filepath = utils.getPath('/logs/');
  if(!fs.existsSync(filepath)) fs.mkdirSync(filepath);
  var date = new Date();
  var m = date.getMonth() + 1;
  if(m<10) m = '0'+m;
  var d = date.getDate();
  if(d<10) d = '0'+d;

  var errMsg = date.getHours()+':'+date.getMinutes()+':'
    +date.getSeconds()+' 发生严重错误：';
  if(err.message) {
    errMsg += err.message;
  } else {
    errMsg += err;
  }
  errMsg += '\r\n';
  if(err.stack) errMsg += err.stack+'\r\n';
  console.log(errMsg);
  filepath += date.getFullYear()+''+m+''+d+'/';
  if(!fs.existsSync(filepath)) fs.mkdirSync(filepath);
  filepath += global._serverId+'_uncaughtException.txt';
  var writeStream = fs.createWriteStream(filepath, {flags: 'a'});
  try {
    writeStream.write(errMsg, function() {
      writeStream.end();
      writeStream = null;
      filepath = null;

      console.log(global._serverId+ '已停止运行。');
      process.abort();
    });
  } catch(err2) {
    writeStream.end();
    writeStream = null;
    filepath = null;
  }
}

var Tasgine = require('Tasgine');

global.server = new Tasgine();
try {
  global.server.start();
} catch(err) {
  logUncaughtError(err);
}