package nxm.sys.libg;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ComponentEvent;

import nxm.sys.libg.Theme;

/** A class to run a graphical Midas Panel. This class is implemented using
    swing components while {@link MPanel} uses AWT. <br>
    <br>
    Additionally (since NeXtMidas 1.9.2) this class has the ability to act as a
    {@link nxm.sys.libg.MidasFrame} which is used to enable the creation of swing-based Java
    bean components (see {@link MidasBean}).

    @see MWindow
    @see MPanel
    @see MidasBean

    @author  J. Czechowski
    @since   NeXtMidas 1.9.2
 */
public class MidasDisplay extends MJPanel {
  /** NOTE: this should be changed if the structure/fields of this class changes. */
  private static final long serialVersionUID = 2012020910311L; // for Serializable interface

  /** Initializes the display. */
  public MidasDisplay() {
    this("MidasDisplay");
  }

  /** Initializes the display.
      @param name The registry name to use.
   */
  protected MidasDisplay(String name) {
    super(name);
    setBackground(Color.black);
    setForeground(Color.red);
    //setBorder(BorderFactory.createLineBorder(Color.black));  //JWB: removed in 2.7.3 (Bug 1561)
    this.setSize(100, 100);
    this.setPreferredSize(new Dimension(100, 100));
    this.setLayout(new GridLayout(1,1));
    addComponentListener(this);
    Theme.initialize();  // Make sure the theme is set. Bug 2348
  }

  /** Paint the MidasDisplay */
  public void paintComponent (Graphics g) {
    if (getComponents().length == 0) paintComponentBasic(g, getTitle()+": Close Popup to push back into panel");
    else { super.paintComponent(g); }
  }

  /** Adds a MWindow on to the display. This method is loosely based on the
      Pane.add(MWindow) method in PANEL
      @param mw The MWindow to attach
      @since NeXtMidas 2.7.3
   */
  void add (MWindow mw) {          // Package-private only used by MWindow
    if (mw.MW == null) mw.MW = mw;  // needed to avoid NPE
    setMWindow(mw);
    mw.isMidasDisplayWithSwingPopups = Theme.getOption(Theme.SWINGPOPUPS); // If using swing popups, we need to let MWindow know that this is a MidasDisplay Since 3.8.1
    mw.setSize(getWidth(), getHeight());
    add(mw.panel);
    mw.process("REFRESH", 0); // since 3.1.1: patch from Michael Ihde to allow proper refreshes in Eclipse RCP
  }

  public void componentResized (ComponentEvent e) {
    // isVisible check added for BUG 2200
    if (MW != null && MW.isPanelVisible()) MW.setSize(getWidth(), getHeight()); // needed to make the MW panel resize with the MidasDisplay
  }

  /** Gives the string identifier of this instance.
      @return A string version of this class.
   */
  public String toString() {
    return this.getClass().getName();
  }
}
