package nxm.sys.libg;

import java.awt.Graphics;

import nxm.sys.inc.MessageHandler;
import nxm.sys.inc.ProvisionalUseOnly;

/**
  A class to implement a panel for other graphics in a graphical control widget.
  @author Jeff Schoen
*/
public class GPanel extends GWidget {

  private MWindow window;      // The window displayed in this panel.
  private int saveHeight = -1; // Height of window in un-poped state (-1 if not set).
  private int saveWidth  = -1; // Width  of window in un-poped state (-1 if not set).

  /**
      Instantiate a new GPanel and initialize parameters.
      @param parent the parent object
      @param name the name of this panel
      @param pw the panel width
      @param ph the panel height
      @param flags widget flags
      @param mh the MessageHandler for this panel
  */
  public GPanel (Object parent, String name, int pw, int ph, int flags, MessageHandler mh) {
    super("GPanel",parent,name,flags,mh);
    open (name, pw, ph);
    addTo (parent);
  }

  @Override
  public void setup() {
    super.setup();
    setWindowSize(false);
    layout();
  }

  @Override
  public void resize (int mode) {
    super.resize(mode);
    setWindowSize(false);
  }

  /**
     Add the given MWindow to this panel.
     @param mw the window to be added
   */
  public void addWindow (MWindow mw) {
    panel.add(mw.panel);  // Add the window to the GPanel, NOT the LayeredPane above it...
    //addOn(mw.panel);
    window = mw;
    setWindowSize(true);
    mw.resize(1);
  }

  private void setWindowSize (boolean force) {
    if((window!=null) && ((!window.isPopped()) || force)) {
      if (is(INLINE)) window.setBounds(bw+4,bw+titleh,pw-8,ph);
      else            window.setBounds(bw,bw+titleh,pw,ph);
    }
  }

  /** Update the size of the underlying panel when the Gpanel display gets pushed or popped
      @param pop true for POP, false for PUSH
      @since NeXtMidas 3.3.2
   */
  protected void updateSize (boolean pop) {
    // added for Bug 42
    if (pop && (saveWidth == -1 && saveHeight == -1)) {
      saveHeight = pos.h;
      saveWidth  = pos.w;
      setSize(1,1);
    } else if (pop == false) {
      setSize(saveWidth, saveHeight);
      saveWidth =-1; saveHeight=-1;
    }
    layout();
  }


  /**
   *  @deprecated Since NeXtMidas 3.9.0 to avoid graphical timing issues
   *  use {@link #paintComponent(Graphics)} (for NXM-3213)
   */
  @Deprecated
  public void paint() {

    refresh();
  }

  @ProvisionalUseOnly("Treat this as protected and should only be called by subclass paintComponent methods")
  @Override
  public void paintComponent (Graphics g) {
    super.paintComponent(g);
    if (is(INLINE)) shadowbox(g,0,0,pw,ph,SB_FLAT); // Updated to use g in 3.9.0 for NXM-3213
  }

  @Override
  public String toString() { return "GPanel=[window="+window+"]"; }

}
