/*
 * @(#)MetalworksFrame.java	1.10 99/04/06
 *
 * Copyright 1998 by Team Noriega: Noah Green, John Weber, and Michael Ahern
 *       
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Team Noriega ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with Team Noriega.
 */
package noriega.expresso.client;

import java.net.*;
import java.rmi.*;
import noriega.expresso.protocols.*;
import noriega.expresso.server.*;
import noriega.expresso.structures.*;
import noriega.util.*;
import java.awt.*;
import java.io.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.Date;

import javax.swing.plaf.metal.*;
import java.lang.StackOverflowError;



/**
  * This is the main container frame for the Metalworks demo app
  *
  * @version 1.10 08/26/98
  * @author Team Noriega
  */
public class MetalworksFrame extends JFrame {
	
    //FROM THE TESTCLIENT.JAVA FILE
    //*****************************
    ExpressoServer es;
    ServiceDirectory sd;
    IMAPService imap;
    SmtpService smtp;
    FlagService flags;
    //*****************************

    JMenuBar menuBar;
    JDesktopPane desktop;
    JInternalFrame toolPalette;
    JCheckBoxMenuItem showToolPaletteMenuItem;
    private CustomDialog userID = null;
    private RequestMailboxDialog rmd = null;
    private Frame frame;
    private String serverHost = "testServer";
    private String user = null;
    

    static final Integer DOCLAYER = new Integer(5);
    static final Integer TOOLLAYER = new Integer(6);
    static final Integer HELPLAYER = new Integer(7);

    static final String ABOUTMSG = "Expresso Mail System \n \nAn application written to show off " +
	"Internet Mail Protocols. \n" + 
	"\nWritten by Team Noriega\n  Noah Green\n  John Weber\n  Michael Ahern\n";

    static final String SERVERDOWN = "Expresso Mail System \n" + 
	"Server Connect Failure\n\n" + 
	"Remote Services are not Available\n" +
	"Please reboot the server\n";
	
    static final String BADMESSAGE = "Expresso Mail System \n" + 
	"Send Message Error\n\n" + 
	"Please check the email address\n" +
	"and correct for errors\n";
    static final String REMOTEEXCP = "Expresso Mail System \n" + 
	"Remote Exception Error\n\n";
    static final String NOMAIL = "Expresso Mail System \n" + 
	"Empty Mail Box\n\n";
    static final String NEWMAIL = "Expresso Mail System \n" + 
	"You've got new mail!\n";
	
	
	
	
	
    private String userid, password;
    
    //----------------- Menu Items ------------------
    JMenu file, edit, views, tools, compose, help;
    
    public MetalworksFrame(String server) {
        super("Team Noriega Expresso Project");
	serverHost = server;
	
	

        final int inset = 50;
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
	setBounds ( inset, inset, screenSize.width - inset*2, screenSize.height - inset*2 );
	buildContent();
	buildMenus();
	this.addWindowListener(new WindowAdapter() {
	    public void windowClosing(WindowEvent e) {
		quit();
	    }});
	UIManager.addPropertyChangeListener(new UISwitchListener((JComponent)getRootPane()));
    }
    
    protected void buildMenus() {
	menuBar = new JMenuBar();
	menuBar.setOpaque(true);
	file = buildFileMenu();
	edit = buildEditMenu();
	views = buildViewsMenu();
	tools = buildToolsMenu();
	compose = buildComposeMenu();
	help = buildHelpMenu();
	
	// build an array of themes
	MetalTheme[] themes = { new DefaultMetalTheme(),
				new GreenMetalTheme(),
				new AquaMetalTheme(),
				new KhakiMetalTheme(),
				new DemoMetalTheme(),
				new ContrastMetalTheme(),
				new BigContrastMetalTheme(),
				/* myTheme*/ };
 
// put the themes in a menu
	JMenu themeMenu = new MetalThemeMenu("Theme", themes);
	
	menuBar.add(file);
	menuBar.add(edit);
	menuBar.add(views);
	menuBar.add(tools);
	menuBar.add(compose);
	menuBar.add(themeMenu);
	menuBar.add(help);
	setJMenuBar(menuBar);	
	
	SwingWorker worker = new SwingWorker() {			
     public Object construct() {
	 return connectToServer(serverHost); ;}
	}; // end SwingWorker			
	worker.get();
	
	
    }
    
    private Boolean connectToServer(String serverhost) {
	System.err.println(serverhost);
	boolean success = this.getServer(serverhost);
	// returns a boolean so handle appropriately if false
	if(!success){
	    JOptionPane.showMessageDialog(
					  MetalworksFrame.this,
					  SERVERDOWN,	
					  "Expresso Server on " + serverhost + " is down",
					  JOptionPane.ERROR_MESSAGE);
	    
	    System.err.println("Could not establish connection to server\n" +
			       "Please boot the server.");
	    return new Boolean(false);
	}
	return new Boolean(true);
    }
    
    protected JMenu buildFileMenu() {
	JMenu file = new JMenu("File");
	
	JMenuItem open = new JMenuItem("Open");
	JMenuItem login = new JMenuItem("Login");
	JMenuItem quit = new JMenuItem("Quit");
	
	open.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		openDocument();
	    }});
	
	login.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		loginToServer();
	    }});
	
	
	quit.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		quit();
	    }});
	
	file.add(open);
	file.add(login);
	file.addSeparator();
	file.add(quit);
	return file;
    }
    
    protected JMenu buildEditMenu() {
        JMenu edit = new JMenu("Edit");
	JMenuItem selectall = new JMenuItem("Select All");
	JMenuItem selectmarked = new JMenuItem("Select Marked As...");
	JMenuItem delete = new JMenuItem("Delete Selected");
	JMenuItem empty = new JMenuItem("Empty Trash");
	JMenuItem moveto = new JMenuItem("Move to folder...");
	JMenuItem markread = new JMenuItem("Mark as Read");
	JMenuItem markall = new JMenuItem("Mark all as Read");
	JMenuItem markunread = new JMenuItem("Mark as Unread");
	JMenuItem createmarker = new JMenuItem("Create New Message Marker");
	JMenuItem deletemarker = new JMenuItem("Remove Message Marker");
	JMenuItem createbox = new JMenuItem("Create New Mail Box");
	JMenuItem deletebox = new JMenuItem("Delete Mail Box");
	JMenuItem prefs = new JMenuItem("Preferences...");
	
	selectall.setEnabled(false);
	selectmarked.setEnabled(false);
	delete.setEnabled(false);
	empty.setEnabled(false); 
	moveto.setEnabled(false); 	 
	markread.setEnabled(false);
	markall.setEnabled(false); 
	markunread.setEnabled(false);
	createmarker.setEnabled(false); 
	deletemarker.setEnabled(false);
	createbox.setEnabled(false); 
	deletebox.setEnabled(false);
	prefs.setEnabled(true); 
	
	
	selectall.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		selectAllMenu();
	    }});
	
	selectmarked.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		selectMarkedMenu();
	    }});
	delete.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		deleteMenu();
	    }});
	empty.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		emptyMenu();
	    }});
	moveto.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		movetoWindow();
	    }});
	markread.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		markreadMenu();
	    }});
	markall.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		markallMenu();
	    }});
	markunread.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		markunreadMenu();
	    }});
	createmarker.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		createMailBoxMenu();
	    }});
	deletemarker.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		deleteMailBoxMenu();
	    }});
	
	createbox.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		createMailBoxMenu();
	    }});
	deletebox.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		deleteMailBoxMenu();
	    }});
	
	prefs.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		openPrefsWindow();
	    }});
	
	
	selectall.setEnabled(false);
	selectmarked.setEnabled(false);
	delete.setEnabled(false);
	empty.setEnabled(false); 
	moveto.setEnabled(false); 	 
	markread.setEnabled(false);
	markall.setEnabled(false); 
	markunread.setEnabled(false);
	createmarker.setEnabled(false); 
	deletemarker.setEnabled(false);
	createbox.setEnabled(false); 
	deletebox.setEnabled(false);
	prefs.setEnabled(true); 
	
	edit.add(selectall);
	edit.add(selectmarked);
	edit.addSeparator();
	edit.add(delete);
	edit.add(empty);
	edit.addSeparator();
	edit.add(moveto);
	edit.addSeparator();
	edit.add(markread);
	edit.add(markall);
	edit.add(markunread);
	edit.addSeparator();
	edit.add(createmarker);
	edit.add(deletemarker);
	edit.addSeparator();
	edit.add(createbox);
	edit.add(deletebox);
	edit.addSeparator();
	edit.add(prefs);
	return edit;
    }
    
    protected JMenu buildViewsMenu() {
	JMenu views = new JMenu("Views");
	
	JMenuItem inBox = new JMenuItem("Open Mailbox");

	inBox.setEnabled(false);

	
	inBox.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		openInBox();
	    }});
	
	views.add(inBox);

	return views;
    }
    
    protected JMenu buildToolsMenu() {
	tools = new JMenu("Tools");
	JMenuItem send = new JMenuItem("Send Message(s)");
	JMenuItem sendnreceive = new JMenuItem("Send and Receive");
	JMenuItem downloadall = new JMenuItem("Download all");
	
	send.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		sendDocument();
	    }});
	sendnreceive.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		sendnreceiveDocuments();
	    }});
	downloadall.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		downloadall();
	    }});
	
	send.setEnabled(false);
	sendnreceive.setEnabled(false);
	downloadall.setEnabled(false);
	
	tools.add(send);
	tools.add(sendnreceive);
	tools.add(downloadall);
	return tools;
    }
    
    protected JMenu buildComposeMenu() {
	compose = new JMenu("Compose");
	JMenuItem newmessage = new JMenuItem("New Message");
	JMenuItem replytoauthor = new JMenuItem("Reply to Author");
	JMenuItem replytoall = new JMenuItem("Reply to All");
	JMenuItem forward = new JMenuItem("Forward Message");
	
	
	newmessage.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		sendNewMessage();
	    }});
	
	replytoauthor.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		replyToAuthor();
	    }});
	
	replytoall.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		replyToAll();
	    }});
	
	forward.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		forwardMessage();
	    }});
	
	newmessage.setEnabled(false);
	replytoauthor.setEnabled(false);
	replytoall.setEnabled(false);
	forward.setEnabled(false);
	
	compose.add(newmessage);
	compose.addSeparator();
	compose.add(replytoauthor);
	compose.add(replytoall);
	compose.addSeparator();
	compose.add(forward);
	return compose;
    }
    
    
    protected JMenu buildHelpMenu() {
	JMenu help = new JMenu("Help");
	JMenuItem about = new JMenuItem("About Expresso Mail...");
	JMenuItem openHelp = new JMenuItem("Open Help Window");
	
	about.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		showAboutBox();
	    }
	});
	
	openHelp.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		openHelpWindow();
	    }});
	
	help.add(about);
	help.add(openHelp);
	
	return help;
    }
    
    protected void buildContent() {
        desktop = new JDesktopPane();
        getContentPane().add(desktop);
    }
    
    
    //-------------------------------------------------------------	
    //------------- Methods for File Menu -----------------
    //----------------------------------------------------
    
    
    public void openDocument() {
        JFileChooser chooser = new JFileChooser();
	chooser.showOpenDialog(this);
    }
    
    public void loginToServer() {
	this.frame = this;
	if(userID == null) {    
	    userID = new CustomDialog(this.frame, 
				      "Enter UserID and Password",
				      this);
	    userID.pack();
	    userID.setLocationRelativeTo(frame);
	    userID.setVisible(true);
	} else {
	    userID.setVisible(true);
	}
	
	
	    String s = userID.getValidatedText();
	    user = userID.getuserID();
	    
        if (s != null) {
            //The text is valid.
	    System.err.println("User Entered: " + s);
        }
	
    }
    
    public void quit() {
        System.exit(0);
    }
    
    
    
    
    //-------------------------------------------------------------	
    //------------- Methods for Edit Menu -----------------
    //----------------------------------------------------
    public void selectAllMenu() {
        
    }
    public void selectMarkedMenu() {
        
    }
    public void deleteMenu() {
        Message m = getMessageFromTable();
	
    }
    public void emptyMenu() {
        
    }
    public void movetoWindow() {
         Message m = getMessageFromTable();
	 //impl.moveMessage
    }
    public void markreadMenu() {
         Message m = getMessageFromTable();
    }
    public void markallMenu() {
         Message m = getMessageFromTable();
    }
    public void markunreadMenu() {
         Message m = getMessageFromTable();
    }
    public void createMarkerMenu() {
         Message m = getMessageFromTable();
    }
    public void deleteMarkerMenu() {
 
    }
    
    public void createMailBoxMenu() {
	this.frame = this;
	rmd = new RequestMailboxDialog (this.frame,
					"Create New Mailbox",
					"Enter new mailbox name",
					this);
	rmd.pack();
	rmd.setLocationRelativeTo(frame);
	rmd.setVisible(true);

	String newmboxname = rmd.getValidatedText();
	if (newmboxname != null) {
	    try {
		imap.createMailbox (newmboxname);
	    }
	    catch (RemoteException e) {
		e.printStackTrace();
		System.err.println("Remote Exception: " + e.getMessage());
		JOptionPane.showMessageDialog
		    (MetalworksInBox.this,
		     MetalworksFrame.REMOTEEXCP + "\n\n",	
		     "RMI Exception",
		     JOptionPane.ERROR_MESSAGE);
		
	    } 
	    catch (ExpressoServerException e) {
		System.err.println("Remote Exception: " + e.getMessage());
		JOptionPane.showMessageDialog
		    (MetalworksInBox.this,
		     MetalworksFrame.REMOTEEXCP + "\n\n",	
		     "RMI Exception",
		     JOptionPane.ERROR_MESSAGE);
	    }

	    // update the tree
	    JInternalFrame[] openFrame = 
		desktop.getAllFramesInLayer(DOCLAYER.intValue());
	    if(openFrame == null) return;
		
	    int len = openFrame.length;
	    int i = 0;
	    for(i = 0; i < len; i++) {
		if(openFrame[i].isSelected()) break;	
	    }
	    if(i >= len) return; //no frame has focus
	    
	    MetalworksInternalWindow active = 
		(MetalworksInternalWindow) openFrame[i];
	    MetalworksInBox mailbox = (MetalworksInBox) active;
	    mailbox.tree.add( new DefaultMutableTreeNode(new String(newmboxname) ) );
	}


    }

    public void renameMailBoxMenu() {

    }

    public void deleteMailBoxMenu() {        
	
    }
    
    
    public void openPrefsWindow() {
        MetalworksPrefs dialog = new MetalworksPrefs(this);
		dialog.show();
    }
    
    
    //-------------------------------------------------------------	
    //------------- Methods for View Menu -----------------
    //----------------------------------------------------
    public void openInBox() {
		System.err.println("Creating inbox");
		JInternalFrame doc = new MetalworksInBox(this, es, sd, imap,
							 smtp, flags);
	
		try { 
		    desktop.add(doc, DOCLAYER);
		    doc.setSelected(true); 
		} catch (java.beans.PropertyVetoException e2) {
		    // do nothing
		} catch (java.lang.StackOverflowError e3) {
		    System.err.println("Stack Overflow" + e3.getMessage());
		} catch (Exception e) {
		    System.err.println("Stack " + e.getMessage());
		}
    }
    
    public void openOutBox() {
	JInternalFrame doc2 = new MetalworksInBox(this, es, sd, imap,
						  smtp, flags);
	System.err.println("Metal1");
	try { 
	    desktop.add(doc2, DOCLAYER);
	    doc2.setSelected(true); 
	} catch (java.beans.PropertyVetoException e2) {
	    // do nothing
	} catch (java.lang.StackOverflowError e3) {
	    System.err.println("Stack Overflow" + e3.getMessage());
	}
    }
    
    //-------------------------------------------------------------	
    //------------- Methods for Tools Menu -----------------
    //----------------------------------------------------
    public void sendDocument() {
	
	JInternalFrame[] openFrame = 
	    desktop.getAllFramesInLayer(DOCLAYER.intValue());
	if(openFrame == null) return;
		
	int len = openFrame.length;
	int i = 0;
	for(i = 0; i < len; i++) {
	    if(openFrame[i].isSelected()) break;	
	}
	if(i >= len) return; //no frame has focus
	
	MetalworksInternalWindow active = 
	    (MetalworksInternalWindow) openFrame[i];
	String t = active.getType();
	
	if ( t.equalsIgnoreCase("message")) {
	    System.err.println("Closed:" + openFrame[i].getTitle());
	    MetalworksDocumentFrame mess = (MetalworksDocumentFrame) active;
	    DEBUG.debug ("TO: " + mess.getToField());
	    DEBUG.debug ("FROM: " + mess.getFromField());

	    Header h = null;
	    String tofield = tofield = mess.getToField();
	    
	    try {
		h = new Header(	user + "@rbs.edu",
				mess.getToField(),
				mess.getsubField(),
				new Date() );
		
		
	    } 
	    catch (MalformedEmailAddressException e) {
		System.err.println("Email error: " + e.getMessage());
		System.err.println("to address: " + tofield);
		
		JOptionPane.showMessageDialog(MetalworksFrame.this,
					      BADMESSAGE,	
					      "Send Message Error",
					      JOptionPane.ERROR_MESSAGE);
		System.err.println("Not a valid email address");
		return;
	    } 
	    catch (java.net.UnknownHostException e) {
		System.err.println("Email error: " + e.getMessage());
		JOptionPane.showMessageDialog(MetalworksFrame.this,
					      BADMESSAGE + 
					      "\nThe domain is not valid",
					      "Send Message Error",
					      JOptionPane.ERROR_MESSAGE);
		System.err.println("Not a valid domain");
		return;
	    }
	    
	    
	    Message m = new Message( h, mess.getContentField() );
	    try {
		smtp.connect();	
		DEBUG.debug ("SENDING " + m);
		smtp.sendmsg(m);
		openFrame[i].dispose();
		smtp.close();
		
	    } 
	    catch (RemoteException e) {
		System.err.println("Email error: " + e.getMessage());
		JOptionPane.showMessageDialog(MetalworksFrame.this,
					      REMOTEEXCP + "\n\n" + 
					      e.getMessage(),	
					      "RMI Exception",
					      JOptionPane.ERROR_MESSAGE);
		return;
	    } 
	    catch (ExpressoServerException e) {
		JOptionPane.showMessageDialog(MetalworksFrame.this,
					      SERVERDOWN,	
					      "Expresso Server on " + 
					      serverHost + " is down",
					      JOptionPane.ERROR_MESSAGE);
		return;
	    }
	    catch (Exception e) {
		JOptionPane.showMessageDialog(MetalworksFrame.this,
					      SERVERDOWN,	
					      "General Exception " + 
					      serverHost + " is down",
					      JOptionPane.ERROR_MESSAGE);
		return;
	    }
	} 
	else System.err.println
		 ("Not a message window: " + openFrame[i].getTitle());
	
    }

    public void sendnreceiveDocuments() {
		sendDocument();
		downloadall();
    }

    public void downloadall() {
	try {
	
	    int newmessages = imap.checkNewmail();
	    if(newmessages > 0)
		JOptionPane.showMessageDialog(MetalworksFrame.this,
					      NEWMAIL + "There are " + 
				              newmessages + " new messages in your Inbox",	
					  "You've Got Mail! ",
					      JOptionPane.INFORMATION_MESSAGE);    
	    
	} catch (RemoteException e) {
	    System.err.println("Email error: " + e.getMessage());
	    JOptionPane.showMessageDialog(MetalworksFrame.this,
					  REMOTEEXCP + "\n\n" + 
					  e.getMessage(),	
					  "RMI Exception",
					  JOptionPane.ERROR_MESSAGE);
	    return;
	} 
	catch (ExpressoServerException e) {
	    JOptionPane.showMessageDialog(MetalworksFrame.this,
					  SERVERDOWN,	
					  "Expresso Server on " + 
					  serverHost + " is down",
					  JOptionPane.ERROR_MESSAGE);
	    return;
	}
	catch (Exception e) {
	    JOptionPane.showMessageDialog(MetalworksFrame.this,
					  SERVERDOWN,	
					  "General Exception " + 
					  serverHost + " is down",
					  JOptionPane.ERROR_MESSAGE);
	    return;
	}
		
    }
    
    //-------------------------------------------------------------	
    //------------- Methods for Compose Menu -----------------
    //----------------------------------------------------
    
    public void sendNewMessage() {
	JInternalFrame doc = new MetalworksDocumentFrame();
	desktop.add(doc, DOCLAYER);
	try { 
	    doc.setSelected(true); 
	} catch (java.beans.PropertyVetoException e2) {}
    }
    public void replyToAuthor() {
	
	JInternalFrame[] openFrame = 
	    desktop.getAllFramesInLayer(DOCLAYER.intValue());
	if(openFrame == null) return;
		
	int len = openFrame.length;
	int i = 0;
	for(i = 0; i < len; i++) {
	    if(openFrame[i].isSelected()) break;	
	}
	if(i >= len) return; //no frame has focus
	
	MetalworksInternalWindow active = 
	    (MetalworksInternalWindow) openFrame[i];
	String t = active.getType();
	
	if ( t.equalsIgnoreCase("mailbox") ) {
	    System.err.println("Closed:" + openFrame[i].getTitle());
	    MetalworksInBox mailbox = (MetalworksInBox) active;
	    
	    int selectedRow = mailbox.getSelectedRow();
	    
	    Message m =	mailbox.getTableModel().getValuesAt(selectedRow);
	    JInternalFrame doc = new MetalworksDocumentFrame(m, true);
	    desktop.add(doc, DOCLAYER);
	    try { 
		doc.setSelected(true); 
	    } catch (java.beans.PropertyVetoException e2) {}
	}
	
    }
    public void replyToAll() {
	replyToAuthor();
	
    }
    public void forwardMessage() {

	JInternalFrame[] openFrame = 
	    desktop.getAllFramesInLayer(DOCLAYER.intValue());
	if(openFrame == null) return;
	
	int len = openFrame.length;
	int i = 0;
	for(i = 0; i < len; i++) {
	    if(openFrame[i].isSelected()) break;	
	}
	if(i >= len) return; //no frame has focus
	
	MetalworksInternalWindow active = 
	    (MetalworksInternalWindow) openFrame[i];
	String t = active.getType();
	
	if ( t.equalsIgnoreCase("mailbox") ) {
	    System.err.println("Closed:" + openFrame[i].getTitle());
	    MetalworksInBox mailbox = (MetalworksInBox) active;
	    
	    int selectedRow = mailbox.getSelectedRow();
	    
	    Message m =	mailbox.getTableModel().getValuesAt(selectedRow);
	    JInternalFrame doc = new MetalworksDocumentFrame(m, false);
	    desktop.add(doc, DOCLAYER);
	    try { 
		doc.setSelected(true); 
	    } catch (java.beans.PropertyVetoException e2) {}
	}
	
	
    }
    
    //-------------------------------------------------------------	
    //------------- Methods for Help Menu -----------------
    //----------------------------------------------------
    public void openHelpWindow() {
	JInternalFrame help = new MetalworksHelp();
	desktop.add(help, HELPLAYER);
	try { 
	    help.setSelected(true); 
	} catch (java.beans.PropertyVetoException e2) {
	    //do nothing
	}
    }
    
    public void showAboutBox() {
	JOptionPane.showMessageDialog(this, ABOUTMSG);
    }
    
    
    //-------------------------------------------------------------	
    //------------------ Methods for connecting to server ---------
    //-------------------------------------------------------------
    public void setUserAndPassword(String user, String pass) {
	userid = user;
	password = pass;
	System.err.println(userid + " " + password);
	
	try {
	    this.login(userid, password);
	    this.ping();
	}
	catch (Exception e) {
	    System.err.println ("Fatal Error: Could not connect to server");
	    System.err.println (e.getMessage());
	    e.printStackTrace();
	    System.exit(1);
	}
    }
    
    /** Log in to the server, getting the <code>ServiceDirectory</code>
     * and all service implementations remotely. Could easily be copied
     * into any other client implementation.
     * @param username the username to login with
     * @param password the password to login with
     * @exception ExpressoSecurityException if the login is invalid
     * @exception ExpressoServerException application error
     * @exception RemoteException some kind of RMI problem
     */
    public void login (String username, String password) 
	throws RemoteException, ExpressoServerException,
	       ExpressoSecurityException {
	
	System.err.println(username + " " +  password);
	
	//TODO: move enableMenuItems into try statement
	enableMenuItems();
	try {
	    System.err.println ("Trying to get sd");
	    sd    = es.getServiceDirectory (username, password);
	    
	    System.err.println ("Trying to get imap");
	    imap  = (IMAPService) sd.getService 
		(ExpressoConstants.IMAP_SERVICE_NAME);
	    
	    System.err.println ("Trying to get smtp");
	    smtp  = (SmtpService) sd.getService 
		(ExpressoConstants.SMTP_SERVICE_NAME);
	    
	    System.err.println ("Trying to get flags");
	    flags = (FlagService) sd.getService 
		(ExpressoConstants.FLAG_SERVICE_NAME);
	} catch (RemoteException w) {
	    System.err.println("Server Login failed:" + w.getMessage());
	} catch (ExpressoServerException w) {
	    System.err.println("Server Login failed:" + w.getMessage());
	} catch (ExpressoSecurityException w) {
	    System.err.println("Server Login failed:" + w.getMessage());
	} catch (Exception w) {
	    System.err.println("Server Login failed:" + w.getMessage());
	}
    }
    
    /** Pings all the services to see if they are alive. Just produces
     * output to <code>stdout</code>.
     * @exception RemoteException some kind of RMI problem
     */
    public void ping () throws RemoteException {
	try {
	    if (sd.ping()) { 
		System.out.println ("ServiceDirectory Alive"); 
		System.out.println (sd.getServiceInfo());
	    }
	    if (imap.ping()) { 
		System.out.println ("IMAP Alive"); 
		System.out.println (imap.getServiceInfo());
	    }
	    if (smtp.ping()) { 
		System.out.println ("SMTP Alive"); 
		System.out.println (smtp.getServiceInfo());
	    }
	    if (flags.ping()) { 
		System.out.println ("Flags Alive"); 
		System.out.println (flags.getServiceInfo());
	    }
	} catch (RemoteException e) {
	    System.err.println("Ping failed: " + e.getMessage());	
	} catch (NullPointerException e) {
	    System.err.println("Ping failed Null Pointer: " + e.getMessage());	
	} catch (Exception e) {
	    System.err.println("Ping failed General Exception: " + e.getMessage());	
	}
    }
    
    
    private boolean getServer(String server) {
	// First get an instance of the server
	try {
	    es = (ExpressoServer) Naming.lookup 
		("rmi://" + server + ":" + 
		 ExpressoConstants.EXPRESSO_PORT + "/" +
		 ExpressoConstants.EXPRESSO_SERVER_NAME);	
	    return true;
	} catch (Exception e) {
	    System.err.println("Server connect failed" + e.getMessage());
	    return false;
	}
    }
    
    public void enableMenuItems() {
	
	int i, count;

	// diable the login button
	file.getItem(1).setEnabled(false);
	
	count = edit.getItemCount() - 1;
	for(i = 0; i < count; i++) {
	    edit.getItem(i).setEnabled(true);	
	}
	
	count = views.getItemCount();
	for(i = 0; i < count; i++) {
	    views.getItem(i).setEnabled(true);	
	}
	
	count = tools.getItemCount();
	for(i = 0; i < count; i++) {
	    tools.getItem(i).setEnabled(true);	
	}
	
	count = compose.getItemCount();
	for(i = 0; i < count; i++) {
	    compose.getItem(i).setEnabled(true);	
	}
    }


    public Message getMessageFromTable() {
	
	JInternalFrame[] openFrame = 
	    desktop.getAllFramesInLayer(DOCLAYER.intValue());
	if(openFrame == null) return;
		
	int len = openFrame.length;
	int i = 0;
	for(i = 0; i < len; i++) {
	    if(openFrame[i].isSelected()) break;	
	}
	if(i >= len) return; //no frame has focus
	
	MetalworksInternalWindow active = 
	    (MetalworksInternalWindow) openFrame[i];
	String t = active.getType();
	
	if ( t.equalsIgnoreCase("mailbox") ) {
	    System.err.println("Closed:" + openFrame[i].getTitle());
	    MetalworksInBox mailbox = (MetalworksInBox) active;
	    
	    int selectedRow = mailbox.getSelectedRow();
	    
	    Message m =	mailbox.getTableModel().getValuesAt(selectedRow);
	    return m;
	    
	} else return null;
	
    }
    
	
}






















