package ash.gui.core;
import java.awt.Component;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.ActionListener;
import javax.swing.SwingUtilities;
import javax.swing.JPopupMenu;
import javax.swing.JMenuItem;
import ash.util.Log;

/**
 * ポップアップメニューの作成に使用するベースクラス。
 * メニュー項目の作成にはadd()メソッドを使用する。
 */
@SuppressWarnings("serial")
public class AshPopupMenu extends JPopupMenu implements AshIMenu {
	static public AshPopupMenu create(ActionListener listener) {
		AshPopupMenu popup = new AshPopupMenu();
		popup.setActionListener(listener);
		return popup;
	}
	static public AshPopupMenu create(Component compo, ActionListener listener) {
		AshPopupMenu popup = create(listener);
		popup.setPopupListener(compo);
		return popup;
	}

	private ActionListener listener = GUIAdapter.getListener();
	private Component popupArea;

	class PupupMouseAdapter extends MouseAdapter {} // マーカークラス

	// マウスプレスでポップアップメニューを表示するように設定する。
	private PupupMouseAdapter popupLauncher = new PupupMouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if(SwingUtilities.isRightMouseButton(e)) {
					if(AshPopupMenu.this.getComponentCount() != 0) {
						popupSelected(e);
						show(popupArea, e.getX()+4, e.getY()-4);
					}
				}
			}};

	public AshPopupMenu() { construct(); }

	public AshPopupMenu(Component popupArea) {
		construct();
		setPopupListener(popupArea);
	}

	protected void construct() {}

	public void setPopupListener(Component popupArea) {
		this.popupArea = popupArea;
		for(MouseListener ml : popupArea.getMouseListeners()) {
			if(ml instanceof PupupMouseAdapter) {
				if(ml == popupLauncher) return;
				Log.debug(101, "AshPopupMenu#setPopupListener(): " + ml);
				popupArea.removeMouseListener(ml);
			}
		}
		popupArea.addMouseListener(popupLauncher);
	}

	public void setActionListener(ActionListener listener) {
		this.listener = listener;
	}

	protected void popupSelected(MouseEvent me) {}

	public JMenuItem add(String name, String action) {
		return add(name, action, listener);
	}

	protected JMenuItem add(String name, String action, ActionListener listener){
		JMenuItem menuItem = new JMenuItem();
		menuItem.setText(name);
		menuItem.setActionCommand(action);
		menuItem.addActionListener(listener);
		add(menuItem);
		return menuItem;
	}
}

