package com.srbenoit.filter;

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;

/**
 * A class that displays a file chooser dialog in the AWT event thread.
 */
public class DirectoryAsker implements Runnable {

    /** the dialog title */
    private transient String title;

    /** the selected directory */
    private transient File dir;

    /**
     * Shows the dialog, waits for the user response, and returns the selection.
     *
     * @param   dialogTitle  the dialog title
     * @return  the selected directory, or <code>null</code> if the user canceled
     */
    public File askDir(final String dialogTitle) {

        this.title = dialogTitle;
        this.dir = null;

        try {
            SwingUtilities.invokeAndWait(this);
        } catch (Exception e) {
            this.dir = null;
        }

        return this.dir;
    }

    /**
     * Constructs the user interface in the background and gets the user's selection.
     */
    public void run() {

        JFileChooser chooser;
        int result;

        chooser = new JFileChooser();
        chooser.setDialogTitle(this.title);
        chooser.setMultiSelectionEnabled(false);
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        result = chooser.showOpenDialog(null);

        if (result == JFileChooser.APPROVE_OPTION) {
            this.dir = chooser.getSelectedFile();
        } else {
            this.dir = null;
        }
    }
}
