/*
 * jNPad v0.3 - jNPad's an Simple Text Editor written in Java
 *
 * Copyright (C) 2014-2017  rgs
 *
 * Require JDK 1.6 (or later)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 *
 * Info, Questions, Suggestions & Bugs Report to rgsevero@gmail.com
 */

package jnpad.ui.toolbar;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;

/**
 * The Class PopupButton.
 *
 * @version 0.3
 * @since   jNPad v0.1
 */
public class PopupButton extends ToolBarButton {
  private JPopupMenu        popupMenu;

  /** UID */
  private static final long serialVersionUID = 4580717688029218972L;

  /**
   * Instantiates a new popup button.
   */
  public PopupButton() {
    super();
    
    setAction(new AbstractAction() {
      private static final long serialVersionUID = -4411577926241845090L;

      @Override
      public void actionPerformed(ActionEvent e) {
        showPopup();
      }
    });
  }

  /**
   * Instantiates a new popup button.
   *
   * @param popup JPopupMenu
   * @param icon Icon
   */
  public PopupButton(JPopupMenu popup, Icon icon) {
    this();
    popupMenu = popup;
    setIcon(icon);
  }

  /**
   * Gets the popup menu.
   *
   * @return JPopupMenu
   */
  public JPopupMenu getPopupMenu() {
    return popupMenu;
  }

  /**
   * Sets the popup menu.
   *
   * @param popup JPopupMenu
   */
  public void setPopupMenu(JPopupMenu popup) {
    popupMenu = popup;
  }

  /**
   * Sets the icon.
   *
   * @param icon the new icon
   * @see javax.swing.AbstractButton#setIcon(javax.swing.Icon)
   */
  @Override
  public final void setIcon(Icon icon) {
    if (icon instanceof ImageIcon) {
      super.setIcon(new DropDownIcon((ImageIcon) icon));
    }
    else {
      super.setIcon(icon);
    }
  }

  /**
   * Show popup.
   */
  protected void showPopup() {
    if (popupMenu != null) {
      SwingUtilities.updateComponentTreeUI(popupMenu);
      popupMenu.pack();
      popupMenu.show(this, 0, getHeight());
    }
  }

}
