/**
 * Created by xaj on 2017/6/6.
 */
const schedule = require('node-schedule');
const fs       = require('fs');
const path     = require('path');
const moment   = require('moment');
const config   = require('config');
const basic    = require('../middlewares/_pub').basic;

const process  = require('child_process');

/*每分钟的第30秒触发： '30 * * * * *'
 每小时的1分30秒触发 ：'30 1 * * * *'
 每天的凌晨1点1分30秒触发 ：'30 1 1 * * *'
 每月的1日1点1分30秒触发 ：'30 1 1 1 * *'
 2016年的1月1日1点1分30秒触发 ：'30 1 1 1 1 2016'
 每周1的1点1分30秒触发 ：'30 1 1 * * 1'*/
function BeginCleanLogWork(timeInterval){
    schedule.scheduleJob(timeInterval, cleanLogJob);
}

function BeginCleanPm2LogWork(){
    schedule.scheduleJob('00 00 00 1 * *', cleanPm2LogJob);
}

function cleanLogJob() {
    console.log('[cleanLogJob] BeginDayWork:' + new Date());

    let servicName = config.get('log4jsName');
    let dateMoment = moment(new Date()).subtract(3, 'days').format('YYYYMMDD');
    let fileName = basic.getLocalIP('eth', 'IPv4') + '-' + servicName + '-' + dateMoment + '.log';
    let filePath = path.join('./logs/' + fileName);
    console.log(fileName)
    console.log(filePath)

    if (fs.existsSync(filePath)) {
        fs.unlink(filePath, function (err) {
            if (err) {
                console.error('[cleanLogJob] 清除3天前日志失败，原因：' + JSON.stringify(err));
            }
            else {
                console.log('[cleanLogJob] 清除3天前日志成功，被清除日志：' + fileName);
            }
        })
    }
    else {
        console.error('[cleanLogJob] 日志文件: %s 不存在', filePath);
    }

}


function cleanPm2LogJob() {
    process.exec('pm2 flush', function (error, stdout, stderr) {
        if (error) {
            console.log('[cleanPm2LogJob] exec error: ' + error);
        }
        else {
            console.log(stdout);
            console.log(stderr);
        }
    });
}

// BeginCleanLogWork();

module.exports = {
    "BeginCleanLogWork": BeginCleanLogWork,
    "BeginCleanPm2LogWork": BeginCleanPm2LogWork
};
