package relational.email;

import java.net.*;
import java.rmi.*;
import java.lang.reflect.Field;
import java.util.Vector;
import relational.*;
import javax.swing.*;

/**
 * Instantiate from the Unix command line a graphical application that
 * reads and composes email using the relational email database schema.
 */
public class Email {
	static DisplayManager dm;

	public static DisplayManager getDisplayManager() {
		return dm;
	}

	public static void main(String[] args) {
		try {
			// install our private table UI. Too bad this trick
			// isn't portable across L&F's; but the trick is necessary
			// to work around a buggy interaction between selection &
			// drag 'n drop.
			javax.swing.UIManager.put("TableUI",
				"relational.email.DragTableUI");

			Database db;
			if (args[0].equals("remote")) {
				// use remote database; data should already be there
				InetAddress thisHost = InetAddress.getLocalHost();
				db = (Database)
					Naming.lookup("//"+thisHost.getHostName()+"/RMIDatabase");
			} else {
				// use local database; import it myself
				db = new InternalDatabase();
	
				System.err.println("importing...\n");
				Vector mv = Mailbox.importMail(db, args[0]);
			}
	
			System.err.println("indexing...\n");
			// These are idempotent (they do nothing if the index exists)
			db.createIndex(Body.f_msg);
			db.createIndex(Header.f_msg);
			db.createIndex(Header.f_value);
			db.createIndex(Header.f_name);
	
			System.err.println("displaying...\n");

			if (args.length>=2 && args[1].equals("window")) {
				dm = new WindowDisplayManager();
			} else {
				dm = new TileDisplayManager();
			}
			System.err.println("mgr is "+dm.getClass());

			FilterView fv = new FilterView();

			// MenuPanel
			// CommandPanel cp = new CommandPanel(fv.getWherePanel());
			MenuPanel mp = new MenuPanel(fv.getWherePanel());
			dm.add(mp, "Command Panel");
			dm.registerKeyboardAction(mp,
				"select",
				KeyStroke.getKeyStroke(';'),
				JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

			FilterModel fm = (FilterModel) fv.getModel();
			fm.setDatabase(db);

			// FilterView
			dm.add(fv, "Filter View");

			// MessageView
			MessageView mview = new MessageView();
			mview.setVisible(true);
			fv.setMessageViewer(mview);

			dm.add(mview, "Message View");

			dm.setVisible(true);
		} catch (Exception ex2) {
			ex2.printStackTrace();
		}
	}
}
