/*
 * Written by Dawid Kurzyniec and released to the public domain, as explained
 * at http://creativecommons.org/licenses/publicdomain
 */

package edu.emory.mathcs.util.swing;

import java.awt.*;
import javax.swing.*;
import javax.swing.text.Document;
import javax.swing.text.BadLocationException;

/**
 * A a small dialog allowing to collect a password in a secure way.
 *
 * @author Dawid Kurzyniec
 * @version 1.0
 */
public class PasswdPanel extends JPanel {
    JPasswordField pwd = new JPasswordField(30);

    public PasswdPanel(JComponent label) {
        setLayout(new BorderLayout());
        add(label, BorderLayout.NORTH);
        add(pwd, BorderLayout.CENTER);
    }

    public void destroy() {
        Document doc = pwd.getDocument();
        try {
            doc.remove(0, doc.getLength());
        }
        catch (BadLocationException e) {
            // can't happen
            throw new RuntimeException(e);
        }
    }

    public char[] getPassword() {
        return pwd.getPassword();
    }

    public JOptionPane newPasswdPane() {
        JOptionPane pane = new JOptionPane(this, JOptionPane.QUESTION_MESSAGE,
                                           JOptionPane.OK_CANCEL_OPTION);
        return pane;
    }

    public static char[] askPassword(JComponent parent, String caption,
                                     String label) {
        return askPassword(parent, caption, new JLabel(label));
    }

    public static char[] askPassword(JComponent parent, String caption,
                                     JComponent label) {
        PasswdPanel p = new PasswdPanel(label);
        JOptionPane pane = p.newPasswdPane();
        JDialog dialog = pane.createDialog(parent, caption);
        p.pwd.requestFocus();
        try {
            dialog.show();
            dialog.dispose();
            Object selectedValue = pane.getValue();
            if (selectedValue == null) return null;
            int action = ((Integer)selectedValue).intValue();
            return (action == JOptionPane.OK_OPTION) ? p.pwd.getPassword() : null;
        }
        finally {
            p.destroy();
        }
    }
}
