const fs = require('fs') ;
const path = require('path');
const utils = require('./utils.js');

var Logger = function () {
  this.logs = [];
  this.isRunning = true;
};

module.exports = Logger;

Logger.prototype.log = function(msg) {
  this.logs.push({time:new Date(),msg:msg});
};

Logger.prototype.logError = function(err) {
  this.log(err.message);
  this.log(err.stack);
};

Logger.prototype.start = function() {
  this.writeLog();
};

Logger.prototype.writeLog = function() {
  var self = this;
  if(self.logs.length==0) {
    setTimeout(function() {
      self.writeLog();
    }, 1000);
    return;
  }
  var log = self.logs.shift();
  var str = '';
  if(typeof log.msg === 'string') {
    str = log.msg;
  } else {
    str = JSON.stringify(log.msg);
  }
  var tempDir = global.tempDir+"/";
  if(!fs.existsSync(tempDir)) fs.mkdirSync(tempDir);
  var filepath = tempDir+'log/';
  if(!fs.existsSync(filepath)) fs.mkdirSync(filepath);
  filepath += utils.formatDate(log.time, 'yyyy_MM_dd')+'.txt';
  var writeStream = fs.createWriteStream(filepath, {flags: 'a'});
  try {
    writeStream.write(utils.formatDate(log.time, 'hh:mm:ss:S')+' '+str+'\r\n', function() {
      writeStream.end();
      writeStream = null;
      filepath = null;
      str = null;
      if(self.isRunning) self.writeLog();
    });
  } catch(err) {
    writeStream.end();
    writeStream = null;
    filepath = null;
    str = null;
    if(self.isRunning) self.writeLog();
  }
};
