package relational.email;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

/**
 * A display manager that tiles the various GUI panels together in a
 * single window.
 */
public class TileDisplayManager
	implements DisplayManager {

	JFrame theFrame;
	FilterView myFilterView;
	MessageView myMessageView;

	TileDisplayManager() {
		theFrame = new JFrame("Email");

		theFrame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				Window w = e.getWindow();
				w.setVisible(false);
				w.dispose();
				System.exit(0);	//ouch
			}
		});

		theFrame.setContentPane(new JPanel() {
			public boolean isFocusTraversable() { return true; } });

		// BoxLayouts are good. FlowLayouts are bad.
		theFrame.getContentPane().setLayout(
			new BoxLayout(theFrame.getContentPane(), BoxLayout.Y_AXIS));
		theContent = null;

		theFrame.setLocation(200, 200);
	}

	static class TestyListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			System.err.println("Performed: "+e);
		}
	}

	JComponent theContent;

	public void add(JComponent c, String title) {
		JPanel borderedPane = new JPanel();
		borderedPane.setLayout(new BoxLayout(borderedPane, BoxLayout.Y_AXIS));
		borderedPane.setBorder(BorderFactory.createTitledBorder(title));
		borderedPane.add(c);
		if (theContent==null) {
			theContent = borderedPane;
		} else {
			theFrame.getContentPane().remove(theContent);
			JSplitPane jsp =
				new JSplitPane(JSplitPane.VERTICAL_SPLIT,
					theContent, borderedPane);
			theContent = jsp;
			jsp.setDividerLocation(400);
		}
		theFrame.getContentPane().add(theContent);

		if (c instanceof FilterView) {
			myFilterView = (FilterView) c;
		}
		if (c instanceof MessageView) {
			myMessageView = (MessageView) c;
		}
	}

	public void setVisible(boolean state) {
		theFrame.setVisible(state);
		if (state==true) {
			theFrame.setSize(theFrame.getPreferredSize());
				// have to setSize after setVisible, because until you setVisible,
				// the frame doesn't count its window decoration size, which
				// count against the setSize() parameter. (yuk.)
			JComponent contentPane = ((JComponent) theFrame.getContentPane());
			contentPane.setRequestFocusEnabled(true);
			contentPane.requestFocus();
		}
	}

	public void registerKeyboardAction(ActionListener a, String s,
		KeyStroke k, int c) {
		JComponent contentPane = ((JComponent) theFrame.getContentPane());
		contentPane.registerKeyboardAction(a, s, k, c);
	}

	public FilterView getFilterView() {
		return myFilterView;
	}

	public MessageView getMessageView() {
		return myMessageView;
	}
}
