package sim;

import java.awt.*;

import java.awt.event.*;

import sim.util.ImagePanel;
import sim.util.DialogButton;

public class OkWindow extends Dialog implements ActionListener {

	private Label description = new Label();
	private Label message = new Label();
	private ImagePanel icon = new ImagePanel(GuiFileLink.getImage("sim/images/Exclaim.gif"));
	private int widthInset = 5;
	private int heghtInset = 10;
	private int width;
	private int height;

	public OkWindow(Frame f) {
		super(f);
		this.setBackground(MainWindow.BACKGROUND);
		this.setLayout(new GridBagLayout());
		this.setResizable(false);
		this.setModal(true);

		GridBagConstraints constrains = new GridBagConstraints();
		constrains.anchor = GridBagConstraints.CENTER;
		constrains.fill = GridBagConstraints.NONE;
		constrains.gridx = 0;
		constrains.gridy = 0;
		constrains.gridwidth = 1;
		constrains.gridheight = 2;
		this.add(this.icon, constrains);

		constrains.anchor = GridBagConstraints.WEST;
		constrains.gridx = 1;
		constrains.gridheight = 1;
		constrains.insets = new Insets(this.heghtInset, this.widthInset, 0, this.widthInset);
		this.add(this.description, constrains);

		constrains.gridy = 1;
		constrains.insets = new Insets(0, this.widthInset, 0, this.widthInset);
		this.add(this.message, constrains);

		constrains.gridx = 0;
		constrains.gridy = 2;
		constrains.gridwidth = 2;
		constrains.insets = new Insets(this.heghtInset, 0, this.heghtInset, 0);
		constrains.anchor = GridBagConstraints.CENTER;
		DialogButton ok = new DialogButton("OK");
		ok.addActionListener(this);
		this.add(ok, constrains);


		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				setVisible(true);
			}
		});
	}

	public void setVisible(boolean visible) {
		if (visible) {
			this.configure();
			this.setLocation(MainWindow.getMiddleOfScreen(this));
		}
		super.setVisible(visible);
	}

	public void addNotify() {
		super.addNotify();

		this.width = 120 + this.icon.getSize().width + 2 * this.widthInset + this.getInsets().left + this.getInsets().right;
		this.height = 80 + this.icon.getSize().height + 2 * this.heghtInset + DialogButton.HEIGHT + this.getInsets().top + this.getInsets().bottom;

		this.configure();
		this.setLocation(MainWindow.getMiddleOfScreen(this));
	}

	private void configure() {
		FontMetrics fm = this.getFontMetrics(this.description.getFont());

		int messageWidth = Math.max(fm.stringWidth(this.description.getText()), fm.stringWidth(this.message.getText()));

		this.description.setSize(messageWidth, fm.getAscent());
		this.message.setSize(messageWidth, fm.getAscent());

		this.setSize(this.width + messageWidth, this.height);
		this.doLayout();
	}

	public void actionPerformed(ActionEvent e) {
		this.setVisible(false);
	}

	public void setDescription(String s) {
		this.description.setText(s);
	}

	public void setMessage(String s) {
		this.message.setText(s);
	}
}
