package relational.email;

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

/**
 * A class for debugging the Where clauses. The sophistication of the
 * relational database package grew as the email package asked more and
 * more of it. Inverting queries was surprisingly tricky.
 */
public class Test {
	public static void main(String[] args) {
		try {
			Database db;
			if (args.length>=1 && args[0].equals("remote")) {
				// use remote database; data should already be there
				InetAddress thisHost = InetAddress.getLocalHost();
				db = (Database)
					Naming.lookup("//"+thisHost.getHostName()+"/RMIDatabase");
			} else {
				db = new InternalDatabase();
				Mailbox.importMail(db, args.length>=1?args[0]:"/tmp/brief");
				db.createIndex(Header.f_msg);
				db.createIndex(Header.f_value);
			}
	
			Where w1 = 
				new WhereOr(
					new WhereEquals(Header.f_msg, new Integer(3249)),
					new WhereOr(
						new WhereEquals(Header.f_msg, new Integer(6507)),
						new WhereOr(
							new WhereEquals(Header.f_msg, new Integer(4061)),
							new WhereEquals(Header.f_msg, new Integer(2430))
						)
					)
				);
			Where w2 =
				new WhereOr(
					new WhereEquals(Header.f_name, "From"),
					new WhereOr(
						new WhereEquals(Header.f_name, "Subject"),
						new WhereOr(
							new WhereEquals(Header.f_name, "Date"),
							new WhereEquals(Header.f_name, "Length")
						)
					)
				);
			Where w3 = new WhereAnd(w1, w2);

			Select sel = new Select(Header.class, w3);

			ResultSet rs = sel.evaluate(db);

			System.out.println("got "+rs.size()+" results");
			Iterator iter = rs.iterator();
			while (iter.hasNext()) {
				Relational ro = (Relational) iter.next();
				String name = (String) Header.f_name.get(ro);
				String value = (String) Header.f_value.get(ro);
				System.out.println(name+": "+value);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
