/**
 * SimpleAuthenticatorjava.java
 *
 * @author Created by Omnicore CodeGuide
 */

package edu.sc.seis.gee;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;



public class SimpleAuthenticator extends Authenticator {

    protected PasswordAuthentication getPasswordAuthentication() {
        final JDialog jd = new JDialog(FrameManager.getManager().getCurrentMainFrame(),
                                       "Enter password",
                                       true);
        jd.getContentPane().setLayout (new GridBagLayout());
        String message = "GEE requires a password to access the network. :\n"+
            getRequestingPrompt();
        JLabel jl = new JLabel(message);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.fill = gbc.HORIZONTAL;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        jd.getContentPane().add(jl, gbc);
        gbc.gridwidth = 1;
        gbc.gridy++;
        gbc.gridx = 0;
        JLabel userLabel = new JLabel("User Name:");
        jd.getContentPane().add (userLabel, gbc);
        gbc.gridx++;
        JTextField username = new JTextField();
        jd.getContentPane().add (username, gbc);
        gbc.gridx=0;
        gbc.gridy++;
        JLabel passLabel = new JLabel("Password:");
        jd.getContentPane().add (passLabel, gbc);
        gbc.gridx++;
        JPasswordField password = new JPasswordField();
        jd.getContentPane().add (password, gbc);
        gbc.gridx=0;
        gbc.gridy++;
        gbc.gridwidth = 2;
        JButton jb = new JButton("OK");
        jd.getContentPane().add (jb, gbc);
        jb.addActionListener(new ActionListener() {
                    public void actionPerformed (ActionEvent e) {
                        jd.dispose();
                    }
                });
        jd.pack();
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        jd.setLocation((int)(dim.getWidth()/2),
                           (int)(dim.getHeight()/2));
        jd.setVisible(true);
        return new PasswordAuthentication(username.getText(), password.getPassword());

    }

    /**
     *
     */
    public static void main(String[] args) {
        // just for testing
        Start.main(args);
        JFrame frame = FrameManager.getManager().getCurrentFrame();
        frame.show();
        SimpleAuthenticator auth = new SimpleAuthenticator();
        PasswordAuthentication out = auth.getPasswordAuthentication();
        System.out.println("out "+out.getUserName()+"  "+out.getPassword().equals("test"));
    }

}

