package com.hero.ui.widgets;

import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import javax.swing.Icon;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;

/**
 * Copyright (c) 2000 - 2005, CompNet Design, Inc. All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, is prohibited unless the following conditions are met: 1.
 * Express written consent of CompNet Design, Inc. is obtained by the developer.
 * 2. Redistributions must retain this copyright notice. THIS SOFTWARE IS
 * PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
 * EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * @author CompNet Design, Inc.
 * @version $Revision$
 */

public class PopupMessage extends MessageWindow {

	private static final long serialVersionUID = 8384186899512899068L;

	public static final int TIMEOUT = 2000; // minimum time to show

	private static Hashtable visiblePopups = new Hashtable();

	private static List<String> doNotShow = new ArrayList<String>();

	/**
	 * Returns an instanceof PopupMessage for the given parameters. Allows for
	 * caching of the widgets and tracking of "do not display again"
	 * information.
	 * 
	 * @param owner
	 *            The JFrame that acts as the owner for the window.
	 * @param parent
	 *            The JComponent to center the window around.
	 * @param message
	 *            The message to be displayed.
	 * @param disable
	 *            Whether to allow "do not display this dialog again" option
	 * @return
	 */
	public static PopupMessage getInstance(JFrame owner, JComponent parent,
			String message, boolean disable) {
		message = PopupMessage.removeTabs(message);
		message = PopupMessage.normalizeText(message);
		PopupMessage popup = new PopupMessage(owner, parent, message.trim(),
				disable);
		return popup;
	}

	public static String normalizeText(String message) {
		int index = 0;
		message = message.trim();
		if (message.startsWith("(") && (message.indexOf(")") > 0)) {
			index = message.indexOf(")") + 1;
		}
		if (index <= 0) {
			return message;
		}
		String ret = message.substring(0, index) + "\n\n";
		message = message.substring(index, message.length());
		while (message.indexOf("\n") >= 0) {
			if (message.indexOf("\n") == 0) {
				message = message.substring(1, message.length());
			} else if (message.indexOf("\n") < message.length() - 1) {
				String part1 = message.substring(0, message.indexOf("\n"));
				String part2 = message.substring(message.indexOf("\n") + 1,
						message.length());
				message = part1 + " " + part2;
			} else {
				message = message.substring(0, message.length() - 1);
			}
		}
		while (message.indexOf("\r") >= 0) {
			if (message.indexOf("\r") == 0) {
				message = message.substring(1, message.length());
			} else if (message.indexOf("\r") < message.length() - 1) {
				String part1 = message.substring(0, message.indexOf("\r"));
				String part2 = message.substring(message.indexOf("\r") + 1,
						message.length());
				message = part1 + part2;
			} else {
				message = message.substring(0, message.length() - 1);
			}
		}
		ret += message;
		return ret;
	}

	public static String removeTabs(String message) {
		while (message.indexOf("\t") >= 0) {
			if (message.indexOf("\t") == 0) {
				message = message.substring(1, message.length());
			} else if (message.indexOf("\t") < message.length() - 1) {
				String part1 = message.substring(0, message.indexOf("\t"));
				String part2 = message.substring(message.indexOf("\t") + 1,
						message.length());
				message = part1 + part2;
			} else {
				message = message.substring(0, message.length() - 1);
			}
		}
		return message;
	}

	boolean timesUp = false;

	private JCheckBox disableCB;

	private String message;

	boolean disabled = false;

	private boolean showDisable = false;

	private Icon icon;

	private PopupMessage(JFrame owner, JComponent parent, String message,
			boolean disable) {
		super(owner, parent, message);
		this.message = message.trim();
		showDisable = disable;
		if (disable) {
			icon = UIManager.getIcon("OptionPane.errorIcon");
		} else {
			icon = UIManager.getIcon("OptionPane.informationIcon");
		}
		init();
		initListeners();
	}

	@Override
	protected void init() {
		super.init();
		disableCB = new JCheckBox("Do not show this again");
		disableCB.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				disabled = true;
				PopupMessage.doNotShow.add(message);
				setVisible(false);
			}
		});
		disableCB.setOpaque(false);
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.fill = GridBagConstraints.NONE;
		gbc.anchor = GridBagConstraints.NORTH;
		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.weightx = 0;
		gbc.weighty = 0;
		gbc.insets = new Insets(0, 5, 5, 5);
		getContentPane().add(new JLabel(icon), gbc);
		gbc.gridy = 1;
		gbc.gridwidth = 2;
		gbc.anchor = GridBagConstraints.SOUTH;
		if (showDisable) {
			getContentPane().add(disableCB, gbc);
		}
		pack();
	}

	protected void initListeners() {
		editor.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				setVisible(false);
			}
		});
		editor.addKeyListener(new KeyAdapter() {
		});
		addMouseListener(new MouseAdapter() {
		});
		addKeyListener(new KeyAdapter() {
		});
		addFocusListener(new FocusListener() {
			public void focusGained(FocusEvent e) {

			}

			public void focusLost(FocusEvent e) {
				if (timesUp) {
					setVisible(false);
				}
			}
		});
		addWindowFocusListener(new WindowFocusListener() {
			public void windowGainedFocus(WindowEvent e) {

			}

			public void windowLostFocus(WindowEvent e) {
				if (timesUp) {
					setVisible(false);
				} else {
					toFront();
				}
			}
		});
	}

	@Override
	protected void setParent(JComponent val) {
		parent = val;
	}

	/**
	 * Sets the visibility of the popup.
	 */
	@Override
	public void setVisible(boolean visible) {
		if ((parent == null) || (owner == null) || (message == null)
				|| (message.trim().length() == 0)) {
			return;
		}
		// first dispose of any popups that are already visible...
		if (visible && (PopupMessage.visiblePopups.get(parent) != null)) {
			PopupMessage vis = (PopupMessage) PopupMessage.visiblePopups
					.get(parent);
			if (!vis.message.equals(message)) {
				vis.setVisible(false);
			} else {
				return;
			}
		} else if (!visible && (PopupMessage.visiblePopups.get(parent) != null)) {
			PopupMessage.visiblePopups.remove(parent);
		}
		if (disabled || PopupMessage.doNotShow.contains(message)) {
			super.setVisible(false);
			return;
		}
		if (visible) {
			PopupMessage.visiblePopups.put(parent, this);
		}

		timesUp = true;
		super.setVisible(visible);
		if (visible && showDisable) {
			Toolkit.getDefaultToolkit().beep();
		}
	}
}