package adecWatt.view;

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.List;
import javax.swing.JPopupMenu;
import javax.swing.JTree;

import misc.Util;

import adecWatt.control.AdecWattManager;
import adecWatt.model.AdecWatt;
import adecWatt.model.Unit;
import adecWatt.model.User;

@SuppressWarnings ("serial")
public class JUnitPopup extends JPopupMenu {

    // ========================================
    public JUnitPopup (final AdecWatt adecWatt, JTree jTree, final Unit<?> unit, Point pos) {
	User user = adecWatt.getUser ();
	boolean editor = user.isEditor (unit);
	final List<?> selectedUnits = Arrays.asList (unit);
	Util.addMenuItem (AdecWattManager.actionDisplayUnit, new ActionListener () {
		public void actionPerformed (ActionEvent e) {
		    adecWatt.broadcastDisplay (AdecWattManager.actionDisplayUnit, selectedUnits);
		}
	    }, this);
	if (editor)
	    Util.addMenuItem (AdecWattManager.actionModifyUnit, new ActionListener () {
		    public void actionPerformed (ActionEvent e) {
			adecWatt.broadcastDisplay (AdecWattManager.actionModifyUnit, selectedUnits);
		    }
		}, this);
	if (editor && unit.getParent () != null)
	    Util.addMenuItem (AdecWattManager.actionRenameUnit, new ActionListener () {
		    public void actionPerformed (ActionEvent e) {
			adecWatt.broadcastDisplay (AdecWattManager.actionRenameUnit, selectedUnits);
		    }
		}, this);
	if (user.isDataStructuresManager ()) {
	    Util.addMenuItem (AdecWattManager.actionTransformUnit, new ActionListener () {
		    public void actionPerformed (ActionEvent e) {
			adecWatt.broadcastDisplay (AdecWattManager.actionTransformUnit, unit);
		    }
		}, this);
	}
	if (editor) {
	    if (unit.getParent () != null)
		Util.addMenuItem (AdecWattManager.actionCopyUnit, new ActionListener () {
			public void actionPerformed (ActionEvent e) {
			    adecWatt.broadcastDisplay (AdecWattManager.actionCopyUnit, unit);
			}
		    }, this);
	    Util.addMenuItem (AdecWattManager.actionNewUnit, new ActionListener () {
		    public void actionPerformed (ActionEvent e) {
			adecWatt.broadcastDisplay (AdecWattManager.actionNewUnit, unit);
		    }
		}, this);
	}
	if ((!unit.getRemote () || unit.story.isModified ()) && !user.isVisitorId ())
	    Util.addMenuItem (AdecWattManager.actionPromoteUnit, new ActionListener () {
		    public void actionPerformed (ActionEvent e) {
			adecWatt.broadcastDisplay (AdecWattManager.actionPromoteUnit, unit);
		    }
		}, this);
	if (!unit.getRemote ())
	    Util.addMenuItem (AdecWattManager.actionRemoveUnit, new ActionListener () {
		    public void actionPerformed (ActionEvent e) {
			adecWatt.broadcastDisplay (AdecWattManager.actionRemoveUnit, unit);
		    }
		}, this);
	show (jTree, pos.x, pos.y);
    }

    // ========================================
}
