package org.khelekore.jsizer;

import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;

/** A popup menu handler.  */
class PopupHandler extends MouseAdapter {
    private SizePanel sp;
    
    public PopupHandler (SizePanel sp) {
	this.sp = sp;
    }

    public void mousePressed (MouseEvent e) {
	if (!SwingUtilities.isRightMouseButton(e)) 
	    return;
	JPopupMenu p = new JPopupMenu ();
	p.add (new JMenuItem (new SetNullFilter ()));
	
	List<TreeNode> tns = sp.getNodesAt (e);
	if (!tns.isEmpty ()) {
	    StringBuilder sb = new StringBuilder ();
	    for (TreeNode tn : tns) {
		if (sb.length () > 0)
		    sb.append ('.');
		sb.append (tn.getName ());
		p.add (new JMenuItem (new SetPrefixAction (sb.toString ())));
	    }
	}

	p.show (sp, e.getX (), e.getY ());
    }

    private class SetNullFilter extends AbstractAction {
	private static final long serialVersionUID = 1;	

	public SetNullFilter () {
	    super ("Clear name filter");
	}

	public void actionPerformed (ActionEvent e) {
	    sp.setClassNameFilter (null);
	}
    }

    private class SetPrefixAction extends AbstractAction {
	private static final long serialVersionUID = 1;	
	private String prefix;

	public SetPrefixAction (String prefix) {
	    super ("Set class name filter to: " + prefix);
	    this.prefix = prefix;
	}

	public void actionPerformed (ActionEvent e) {
	    sp.setClassNameFilter (new PrefixFilter (prefix));
	}
    }
}
