package relational.email;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import java.lang.reflect.*;
import java.util.Vector;
import java.rmi.RemoteException;
import relational.*;

/**
 * The view part of the MVC pattern for the query filter control.
 * I guess it's also the controller. Crazy Swing.
 */
public class FilterView extends JPanel {
	JTable table;

	/* inner */ class MessageViewOpener
		implements ListSelectionListener {

		MessageView viewer;
		public MessageViewOpener(MessageView viewer) {
			this.viewer = viewer;
		}

		public void valueChanged(ListSelectionEvent lse) {
			if (lse.getValueIsAdjusting()) {
				// skip intermediate events as user drags mouse
				// return;
			}
			Message m = getSelectedMessage();
			if (m==null) {
				return;
			}
			try {
				viewer.loadMessage(getDatabase(), m);
			} catch (RemoteException ex) { }
			}
	}

	public Database getDatabase() {
		return getModel().getDatabase();
	}

	public Message getSelectedMessage() {
		int row = table.getSelectionModel().getMinSelectionIndex();
		if (row<0) {
			return null;
		}
		return getModel().getMessageAt(row);
	}

	public WherePanel getWherePanel() {
		return wherePanel;
	}
	WherePanel wherePanel;

	public FilterView() {
		super();

		this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

		FilterModel filterModel = new FilterModel();
		table = new DragTable(filterModel);

		JScrollPane jsp = new JScrollPane(table);

		add(jsp);

		wherePanel = new WherePanel();
		wherePanel.setQuery(Where.always());
		add(wherePanel);

/*
		WhereTreeModel wtm = new WhereTreeModel(Where.always());
		JTree jtree = new DragTree(wtm);
		jtree.setCellEditor(new WhereTreeCellEditor());
		jtree.setEditable(true);
//		TreeDropTarget tdt = new TreeDropTarget(jtree);
		jtree.setMinimumSize(new Dimension(400,100));
		jpanel.add(jtree);
*/

/*
		// Arrange for filtermodel (table view) to keep its eye on changes
		// to the tree model (the select(where) clause)
		wtm.addTreeModelListener(filterModel);
		// Fake such a change to kick FilterModel in the behind
		wtm.gratuitousRootEvent();
*/
		wherePanel.addChangeListener(filterModel);
		// Fake a change event to jumpstart FilterModel
		filterModel.stateChanged(new ChangeEvent(wherePanel));

		// add(jpanel, BorderLayout.CENTER);
	}

	public void setMessageViewer(MessageView viewer) {
		ListSelectionModel rsm = table.getSelectionModel();
		rsm.addListSelectionListener(new MessageViewOpener(viewer));
		rsm.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	}

	public FilterModel getModel() { return (FilterModel) table.getModel(); }
}
