const fs = require('fs');
const path = require('path');
const ZIPfolder = path.join(__dirname + '../../minutesFiles/會議記錄壓縮檔');

module.exports = setInterval(() => {
    walkDir(ZIPfolder, (filePath) => {
        fs.stat(filePath, (err, stat) => {
            const now = new Date().getTime();
            const endTime = new Date(stat.mtime).getTime() + 86400000; //1day

            if (err) {
                return console.error(err);
            }

            if (now > endTime) {
                return fs.unlink(filePath, (err) => {
                    if (err) return console.error(err);
                    console.log(`目前時間為${new Date().toLocaleString()}，完成檔案定期清理`);
                });
            }
        });
    });
}, 18000000); //5hr

const walkDir = (dir, callback) => {
    fs.readdirSync(dir).forEach((f) => {
        let dirPath = path.join(dir, f);
        let isDirectory = fs.statSync(dirPath).isDirectory();
        isDirectory ? walkDir(dirPath, callback) : callback(path.join(dir, f));
    });
};
