const libFS   = require("fs");
const libPath = require("path");
const libUtil = require("util");

fcf.module({
  name:         "fcf:NSystem/loggingTasks.js",
  dependencies: [],
  lazy:         [],
  module: function(){
    fcf.application.getCron().append("Clearing log files", "0 1 * * * master", async ()=>{
      let directory  = fcf.getPath(fcf.getDirectory(fcf.application.getConfiguration().logFile));
      let filePrefix = fcf.getFileName(fcf.application.getConfiguration().logFile);
      let files      = await libUtil.promisify(libFS.readdir)(directory);
      await fcf.asyncEach(files, async (a_key, a_fileName)=>{
        if (a_fileName.indexOf(filePrefix) != 0)
          return;
        let stat = await libUtil.promisify(libFS.stat)(libPath.join(directory, a_fileName));
        let lastModifyTime = stat.mtime.getTime();
        let currentTime    = (new Date()).getTime();
        let diff           = (currentTime - lastModifyTime)/1000;
        let lifeTime       = fcf.application.getConfiguration().logLifeTime*24*60*60;
        if (diff > lifeTime)
          await libUtil.promisify(libFS.unlink)(libPath.join(directory, a_fileName));
      });
    });
  }
});
