package org.khelekore.jsizer;

import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

/** A class that lets the user select jar files to add. */
class AddJarAction extends AbstractAction {
    private JFrame f;
    private JSizer js;
    private final JFileChooser chooser = new JFileChooser ();

    private static final long serialVersionUID = 1;

    public AddJarAction (JSizer js, JFrame f) {
	super ("Add jar...");
	this.js = js;
	this.f = f;
    }

    public void actionPerformed (ActionEvent e) {
	chooser.setFileSelectionMode (JFileChooser.FILES_AND_DIRECTORIES);
	JarFileFilter jarFilter = new JarFileFilter ();
	chooser.setFileFilter (jarFilter);
	int returnVal = chooser.showDialog (f, "Select jar file");
	if (returnVal != JFileChooser.APPROVE_OPTION)
	    return;

	File selected = chooser.getSelectedFile ();
	if (selected.isDirectory ()) {
	    boolean added = false;
	    for (File f : selected.listFiles (jarFilter)) {
		added = true;
		js.addJarFile (f, false);
	    }
	    if (added)
		js.runSizer ();
	} else {
	    js.addJarFile (selected, true);
	}
    }

    private static class JarFileFilter extends FileFilter 
	implements java.io.FileFilter {
	@Override public boolean accept (File f) {
	    return f.isDirectory () || isJarFile (f);
	}
	
	private boolean isJarFile (File f) {
	    return f.isFile () && 
		f.getName ().toLowerCase ().endsWith (".jar");
	}

	@Override public String getDescription () {
	    return "Jar files";
	}
    }
}
