import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.net.*;
import javax.swing.*;
import javax.swing.text.html.*;

/**
  This class is a dialog for opening remote pages using
  a url.

  <br><br><a href="../source/LocationDialog.java">View Source File</a>
*/
public class LocationDialog extends JDialog {
  String urlText = "http://";
  JOptionPane optionPane;
  private Mozart mozart;

  public LocationDialog(Mozart moz) {
    super(moz.getFrame(), "Open Location...");
    mozart = moz;

    final String msgString1 = "Enter the URL of the page you wish to open.";
    final JTextField textField = new JTextField(urlText);
    Object[] array = {msgString1, textField};
    
    final String btnString1 = "Enter";
    final String btnString2 = "Cancel";
    Object[] options = {btnString1, btnString2};
    
    optionPane = new JOptionPane(array, 
                                 JOptionPane.QUESTION_MESSAGE,
				 JOptionPane.YES_NO_OPTION,
				 null,
				 options,
				 options[0]);
    setContentPane(optionPane);
    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

    pack();
    setLocationRelativeTo(mozart.getFrame());
    setVisible(false);
  
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent we) {
	/*
	 * Instead of directly closing the window,
	 * we're going to change the JOptionPane's
	 * value property.
	 */
	optionPane.setValue(new Integer(JOptionPane.CLOSED_OPTION));
      }
    });
    
    textField.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
	optionPane.setValue(btnString1);
      }
    });
    
    optionPane.addPropertyChangeListener(new PropertyChangeListener() {
      public void propertyChange(PropertyChangeEvent e) {
	String prop = e.getPropertyName();
	
	if (isVisible() 
	    && (e.getSource() == optionPane)
	    && (prop.equals(JOptionPane.VALUE_PROPERTY) ||
		prop.equals(JOptionPane.INPUT_VALUE_PROPERTY))) {
	  System.out.println("Okay, getting the value...");
	  Object value = optionPane.getValue();
	  
	  if (value == JOptionPane.UNINITIALIZED_VALUE) {
	    //ignore reset
	    System.out.println("Nothing changed, just returning");
	    setVisible(false);
	  }
	  
	  if (value.equals(btnString1)) {
	    System.out.println(btnString1 + " pressed...");
	    urlText = textField.getText();
	    setVisible(false);

	    try {
	      URL url = new URL(urlText);
	      System.out.println(url);
	      mozart.mainFrame.addToDesktop(new MozartInternalFrame(mozart, url));
	    } catch (MalformedURLException urle) {
	      System.out.println("Malformed URL: " + urle);
	    }

	  } else { // user closed dialog or clicked cancel
	    // We'll see what goes here later...
	    System.out.println(btnString2 + " pressed...");
	    setVisible(false);
	  }
	}
      }
    });
  } 
}



