"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoggerPurger = void 0;
const at_1 = require("@f2/at");
const run_1 = require("@f2/run");
const fs_1 = require("@f2/fs");
class LoggerPurger {
    path;
    maxSize;
    maxAge;
    _logger;
    _purgeProcess = new run_1.RunProcess(at_1.Interval.from('2h'), () => {
        return this.purge();
    }, 'log.purge');
    constructor(path, maxSize, maxAge) {
        this.path = path;
        this.maxSize = maxSize;
        this.maxAge = maxAge;
    }
    start(logger) {
        logger.wrapEventEmitter(this._purgeProcess);
        this._logger = logger;
        this._purgeProcess.start();
    }
    stop() {
        this._purgeProcess.stop();
    }
    async purge() {
        const paths = await (0, fs_1.readDir)(this.path, true);
        let toDeletes = [];
        const statsPromises = paths.map(async (path) => {
            const stats = await (0, fs_1.getPathStat)(path);
            return {
                path,
                time: stats.mtime,
                size: stats.size
            };
        });
        const files = await Promise.all(statsPromises);
        files.sort((a, b) => a.time > b.time ? -1 : 1);
        const add = (file) => {
            if (toDeletes.indexOf(file) === -1) {
                toDeletes.push(file);
            }
        };
        if (this.maxAge) {
            const minAt = (0, at_1.subTimeFromNow)(this.maxAge);
            files.map((file) => {
                if (file.time < minAt) {
                    add(file);
                }
            });
        }
        if (this.maxSize) {
            let size = 0;
            files.forEach((f, i) => {
                size += f.size;
                // Les 2 premiers fichiers sont préservés
                if (i <= 1) {
                    return;
                }
                if (size > this.maxSize) {
                    add(f);
                }
            });
        }
        if (toDeletes.length === 0) {
            return;
        }
        this._logger.debug(`Suppression de ${toDeletes.length} fichier(s) de log`);
        const deletePromises = toDeletes.map((f) => (0, fs_1.unlinkIfExists)(f.path));
        await Promise.all(deletePromises);
    }
}
exports.LoggerPurger = LoggerPurger;
