package org.atea.nlptools.macroniser.util;

import java.io.File;
import java.time.Duration;
import java.time.Instant;
import java.util.TimerTask;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Removes old files from a directory at a set interval
 */
public class FileSweeper extends TimerTask
{
    private static final Logger logger = LogManager.getLogger(FileSweeper.class);

    private final File directory;
    private final Duration interval;

    /**
     * Initializes a new instance of the {@link FileSweeper} class.
     * @param directory The directory to sweep.
     * @param deleteOlderThan The duration after which to delete files that have not been modified.
     */
    public FileSweeper(File directory, Duration deleteOlderThan)
    {
        FileUtil.checkValidDir(directory);

        this.directory = directory;
        this.interval = deleteOlderThan;
    }

    @Override
    public void run()
    {
        if (!this.directory.exists())
        {
            logger.warn("The temporary directory has been removed. Cancelling the sweeper task");
            super.cancel();

            return;
        }

        long deleteBefore = Instant.now().minus(this.interval).toEpochMilli();
        final File[] files = this.directory.listFiles();

        for (File file : files)
        {
            if (file.lastModified() < deleteBefore)
            {
                try {
                    FileUtil.deleteFile(file);
                }
                catch (Exception ex) {
                    logger.error("Failed to delete a temporary file", ex);
                }
            }
        }
    }
}
