package relational.email;

import java.awt.event.*;
import java.rmi.RemoteException;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import relational.*;

/**
 * Action handler for composing a new message. Sets up the message
 * pane to accept new text, and configures the ``send'' button.
 */
public class ComposeAction extends AbstractAction {
	Database db;
	Message m;
	boolean reply;

	public ComposeAction(boolean reply) {
		super(reply ? "Reply" : "Compose");
		this.reply = reply;
	}

	public void actionPerformed(ActionEvent e) {
		StringBuffer headerbuf = new StringBuffer();
		if (reply) {
			db = Email.getDisplayManager().getFilterView().getDatabase();
			m = Email.getDisplayManager().getFilterView().getSelectedMessage();
			if (m==null) {
				// TODO: disable unusable menus
				System.out.println("nothing selected");
				return;
			}
			String h1 = getHeader("Reply-to");
			if (h1==null) h1 = getHeader("From");
			if (h1==null) h1 = getHeader("X-BSD-From");
			if (h1==null) {
				System.out.println("no return address");
				return;
			}
			headerbuf.append("To: ");
			headerbuf.append(h1);
			headerbuf.append('\n');

			String h2 = getHeader("Message-ID");
			if (h2!=null) {
				headerbuf.append("In-Reply-To: ");
				headerbuf.append(h2);
				headerbuf.append('\n');
			}

			headerbuf.append("Subject: ");
			String h3 = getHeader("Subject");
			if (h3 != null) {
				if (!h3.toUpperCase().startsWith("RE")) {
					headerbuf.append("Re: ");
				}
				headerbuf.append(h3);
			} else {
				headerbuf.append("your subject-less mail");
			}
			headerbuf.append('\n');
		} else {
			headerbuf.append("To: \nSubject: \n");
		}

		// TODO: these
		headerbuf.append("Date: dummy\n");
		headerbuf.append("Message-ID: dummy\n");

		MessageView mv = Email.getDisplayManager().getMessageView();
		mv.loadMessage(headerbuf.toString(), "");
		mv.setComposing(true);
		// TODO: unselect field in FilterView, since that's not what's
		// in MessageView? or maybe color the messageView the same color
		// as the selection when FilterView is aligned with it.
	}

	protected String getHeader(String name) {
		ResultSet rs = null;
		try {
			rs = db.evaluateSelect(
				new Select(Header.class, Where.and(
					Where.equals(Header.f_msg, m.primaryKey),
					new WhereLike(Header.f_name, name, false, true, true))
				)
			);
		} catch (RemoteException ex) {
		}
		if (rs==null || rs.size()==0) {
			return null;
		}
		return ((Header) rs.getVector().elementAt(0)).value;
	}
}
