import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.concurrent.CountDownLatch;

public class PasswordAsker {

  static String password;
  static JFrame frame;
  static CountDownLatch latch;


  public PasswordAsker() {
    password = null;
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
    latch = new CountDownLatch(1);
  }


  private static void createAndShowGUI() {
    //Create and set up the window.
    frame = new JFrame("Password");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(setMainPane());

    //Display the window.
    frame.pack();
    frame.setVisible(true);
  }


  private static JPanel setMainPane() {
    JPanel rootPanel = new JPanel(false);
    rootPanel.setLayout(new GridLayout(0, 1));

    JPanel infoPanel = new JPanel(false);
    JLabel infoLabel = new JLabel("Please write here the password that you entered for the mySQL root account.\r\nNo information is stored nor sent. I promise.");
    infoPanel.add(infoLabel);

    JPanel passPanel = new JPanel(false);
    passPanel.setLayout(new GridLayout(1, 0));
    JLabel passLabel = new JLabel("password");
    final JTextField passText = new JTextField(20);
    passLabel.setLabelFor(passText);
    passPanel.add(passLabel);
    passPanel.add(passText);

    JPanel  okPanel  = new JPanel(false);
    JButton okButton = new JButton("OK");
    okPanel.add(okButton);

    okButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        password = passText.getText();
        frame.setVisible(false);
        frame.dispose();
        latch.countDown();
      }
    });

    rootPanel.add(infoPanel);
    rootPanel.add(passPanel);
    rootPanel.add(okPanel);

    return rootPanel;
  }


  public boolean waitForPassword() {
    try {
      latch.await();
    }
    catch (InterruptedException e) {
      return false;
    }
    return true;
  }


  public String getPassword() {
    return password;
  }
}
