import java.awt.*;

public class Dlog extends Frame {
	TextField query;
	static boolean done;
	static String answer;
	
	private Dlog(String prompt) {
		super("Read from user");
		
		Panel p;
		GridBagConstraints c;
		Label header;
		
		done = false;
		answer = null;

		c = new GridBagConstraints();
		c.gridx = 0;
		c.gridwidth = 1;
		c.gridheight = 1;
		c.ipady = 5;
		c.anchor = GridBagConstraints.CENTER;
		c.weightx = 1.0;
		
		// create the label giving output to user
		this.setLayout(new GridBagLayout());
		header = new Label(prompt);
		c.gridy = 0;
		c.weighty = 0.0;
		c.fill = GridBagConstraints.HORIZONTAL;
		((GridBagLayout) this.getLayout()).setConstraints(header, c);
		this.add(header);
		
		// create text field to get input from user
		query = new TextField();
		c.gridy = 1;
		c.weighty = 1.0;
		c.fill = GridBagConstraints.HORIZONTAL;
		((GridBagLayout) this.getLayout()).setConstraints(query, c);
		this.add(query);
		
		// finish up
		this.pack();
	}
	
	// action
	//
	// handle button clicks
	public boolean action(Event e, Object arg) {
		String input;
		int num;
		int is_prime;
		
		if(e.target == query) {
			done = true;
			answer = query.getText();
			this.dispose();
			return true;
		} else {
			return false;
		}
	}
	
	// gotFocus
	//
	// sets the default focus location
	public boolean gotFocus(Event e, Object arg) {
		query.requestFocus();
		return true;
	}
	
	public static String getString(String prompt) {
		Dlog f;
		int num = -1;
		boolean ok;
		
		// create the dialog box
		f = new Dlog(prompt);
		f.resize(100, 75);
		f.show();
		
		// wait until user done
		while(done == false) {
			try {
				Thread.sleep(50);
			} catch(InterruptedException e) {
				// Ignore exception
			}
			Thread.currentThread().yield();
		}
		
		return answer;
	}
	
	public static int getInteger(String prompt) {
		String answer;
		
		while(true) {
			answer = getString(prompt);
			
			// translate answer into a number
			try {
				return Integer.parseInt(answer);
			} catch(NumberFormatException dummy) {
				System.err.println("The input is not a number. Try again.");
			}
		}
	}
	
	public static int getInteger() {
		return getInteger("Enter an integer");
	}
	
	public static double getDouble(String prompt) {
		String answer;
		
		while(true) {
			answer = getString(prompt);
			
			try {
				return Double.valueOf(answer).doubleValue();
			} catch(NumberFormatException e) {
				System.err.println("The input is not a number. Try again.");
			}
		}
	}
	
	public static double getDouble() {
		return getDouble("Enter a real number");
	}
	
	public static char getCharacter(String prompt) {
		String answer;
		
		while(true) {
			answer = getString(prompt);
			
			try {
				return answer.charAt(0);
			} catch(StringIndexOutOfBoundsException e) {
				System.err.println("You didn't type anything. Try again.");
			}
		}
	}
	
	public static char getCharacter() {
		return getCharacter("Enter a character");
	}
}
