/* $Id: AutosaveAction.java 901 2015-01-07 13:27:58Z ohura $ */
package smart_gs.swingui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.Comparator;

public class AutosaveAction implements ActionListener {

	public class AutoSaveFileComparator implements Comparator<File> {

		@Override
		public int compare(File o1, File o2) {
			return (int) (o1.lastModified()-o2.lastModified());
		}

	}

	public class AutoSavaFilenameFilter implements FilenameFilter {

		@Override
		public boolean accept(File dir, String name) {
			return (name.startsWith("." + file.getName()) || name.startsWith(file.getName()))
						&& name.endsWith(".auto");
		}

	}

	private File file;

	public AutosaveAction(File file) {
		this.file = file;
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		long time = System.currentTimeMillis() / 1000; // unix time
		File autoSaveDir = new File(file.getParent());
		FilenameFilter filter = new AutoSavaFilenameFilter();
		File[] list = autoSaveDir.listFiles(filter);
		Arrays.sort(list, new AutoSaveFileComparator());
		while(list.length >= 10){
			list[0].delete();
			File[] list1 = new File[list.length-1];
			System.arraycopy(list, 1, list1, 0, list.length-1);
			list=list1;
		}
		WorkspaceWindow.getInstance().saveAll(new File(file.getParent() + "/" + file.getName() + "." + time + ".auto"));
	}

}
