package nuts.core.io;

import nuts.core.log.Log;
import nuts.core.log.Logs;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimerTask;


/**
 * Simple timer class for file delete
 */
public class FileDeleteTask extends TimerTask {
	private final static Log log = Logs.getLog(FileDeleteTask.class);

	private List<File> fileList = new ArrayList<File>();
	
	/**
	 * milliseconds since last modified. (default: 1h) 
	 */
	private long expiredTime = 60 * 60 * 1000;

	/**
	 * @return the expiredTime
	 */
	public long getExpiredTime() {
		return expiredTime;
	}

	/**
	 * @param expiredTime the expiredTime to set
	 */
	public void setExpiredTime(long expiredTime) {
		this.expiredTime = expiredTime;
	}

	/**
	 * add file for delete when expired
	 * @param fileName fileName
	 */
	public void addFile(String fileName) {
		File file = new File(fileName);
		addFile(file);
	}

	/**
	 * add file for delete when expired
	 * @param file file
	 */
	public void addFile(File file) {
		if (file.exists()) {
			file.deleteOnExit();
			synchronized (fileList) {
				fileList.add(file);
			}
		}
	}

	/**
	 * @see java.util.TimerTask#run()
	 */
	@Override
	public void run() {
		synchronized (fileList) {
			long time = Calendar.getInstance().getTimeInMillis();
			
			List<File> removeList = new ArrayList<File>();
			
			for (File f : fileList) {
				if (f.exists()) {
					if (time - f.lastModified() > expiredTime) {
						if (f.delete()) {
							removeList.add(f);
							if (log.isDebugEnabled()) {
								log.debug("File deleted - " + f.getPath());
							}
						}
						else {
							if (log.isWarnEnabled()) {
								log.warn("File delete failed - " + f.getPath());
							}
						}
					}
				}
				else {
					removeList.add(f);
				}
			}
			
			for (File f : removeList) {
				fileList.remove(f);
			}
		}
	}

}
