/**
 * Created by Tony on 2018/7/27.
 */

let fs = require('fs');
let cron = require('node-schedule');
let remove_file_types = [".xlsx", ".pdf", ".jsp"];
function chkIsRemoveType(file) {
    let rst = false;
    for (let fType of remove_file_types) {
        if (file.indexOf(fType) === (file.length - fType.length)) {
            rst = true;
            break;
        }
    }
    return rst;
}
let jobObj = {
    createJob: function (rule, rootPath) {
        let localRule = rule;
        if (!localRule) {
            // setup schedule rule
            localRule = new cron.RecurrenceRule();
            // 3:15AM, everyday
            localRule.dayOfWeek = [1,2,3,4,5,6,0];
            localRule.hour = 3;
            localRule.minute = 15;
        }
        cron.scheduleJob(localRule, function(){
            let path = rootPath;
            fs.exists(path, function (exists) {
                if (exists) {
                    fs.readdir(path, function (err, files) {
                        let currentTime = (new Date()).valueOf();
                        let timeGap = currentTime - (1000 * 60 * 60 * 24 * 0.5); //half day before
                        files.forEach(function(file,index){
                            if (chkIsRemoveType(file)) {
                                let curPath = path + "/" + file;
                                fs.stat(curPath,function(err,data){
                                    if (timeGap > data.mtime) {
                                        fs.unlink(curPath);
                                    }
                                });
                            }
                        });
                    })
                }
            })
        });
    }
};

export default jobObj;