/*
 * Login.java
 *
 * Author: Jonathan Boldiga
 * Date: July 22, 2002
 *
 * Description: This is the login screen for ORBChat, a CORBA based chat program.
 *				This class uses SWING and implements a method called addText() which
 *				grabs the username from the text field and sends it to the client.
 *				To run ORBChat, execute the Client.java class file.
 *
 * Copyright (c) 1993-2001 IONA Technologies PLC.
 *  			All Rights Reserved
 *
*/

package Chat;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import org.omg.CORBA.*;


public class Login extends JFrame{

	Chat.ChatRemote cr;
	ORB newORB;
	protected JTextField userText;
	protected JLabel userLabel;
	protected JButton loginButton;
	protected String user;
	protected String emptyString = "";
    protected String newline = "\n";

	public Login(Chat.ChatRemote cRemote, ORB orb){

		//Do frame stuff.
		super("ORBChat Login");
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});

		//CORBA objects
		cr = cRemote;
		newORB = orb;
		loginButton = new JButton("Login");

		JPanel contentPane = new JPanel();
		contentPane.setLayout(new GridBagLayout());
		contentPane.setBackground(UIManager.getColor("control"));
		GridBagConstraints constraints = new GridBagConstraints();

		constraints.gridx = 0;
		constraints.gridy = GridBagConstraints.RELATIVE;
		constraints.gridwidth = 1;
		constraints.gridheight = 1;
		constraints.insets = new Insets(2, 2, 2, 2);
		constraints.anchor = GridBagConstraints.EAST;

		contentPane.add(userLabel = new JLabel("Username:", SwingConstants.RIGHT), constraints);
		contentPane.add(loginButton = new JButton("Login"), constraints);

		constraints.gridx = 1;
		constraints.gridy = 0;
		constraints.weightx = 1.0;
		constraints.fill = GridBagConstraints.HORIZONTAL;
		constraints.anchor = GridBagConstraints.CENTER;

		contentPane.add(userText = new JTextField(20), constraints);
		constraints.gridx = 1;
		constraints.gridy = GridBagConstraints.RELATIVE;
		constraints.fill = GridBagConstraints.NONE;
		setContentPane(contentPane);

		addText(userText);

	}

	public void addText(final JTextField textF){
		loginButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String text = textF.getText();
				textF.setText("");
				if(text == emptyString){
					JOptionPane.showMessageDialog(new JFrame(), "You must enter a username, goodbye");
					System.exit(0);
				}
				else{
					Chat.ChatLocal cl = (new Chat.ChatClientImpl())._this(newORB);
					cr.enroll(cl, text);
					Chat.Client.runChat(cr, newORB, text, true);
					closeMe();
				}
			}
	    });
	}

	public void closeMe(){
		setVisible(false);
		dispose();
	}

}