package nxm.sys.libg;

import nxm.sys.inc.MessageHandler;
import nxm.sys.lib.Message;

/** A Graphical Progress Monitor/Abort Widget dialog.
    @author Jeff Schoen
*/
public class GProgress extends GDialog {

  GText gtext;
  GValue gval;
  private double val;

  /**
     Instantiate a new GProgress and initialize parameters.
     @param parent the parent Object
     @param name the name of this GProgress
     @param list the button list for the dialog
     @param text the text to be displayed
     @param aw the width
     @param ah the height
     @param flags the gwidget flags
     @param mh the MessageHandler
   */
  public GProgress (Object parent, String name, String list, String text,
                    int aw, int ah, int flags, MessageHandler mh) {
    super(null,name,mh);
    if (ah<=0) ah = text.length()/40+1;
    if (aw<=0) aw = Math.max(40,text.length()/ah);
    // pre estimate total height to reduce resize flicker
    init(list,"",aw*tw,ah*th+(int)(th*2.75),flags);
    int vflags = GValue.GAUGE|GValue.PERCENT|GValue.NOEDIT;
    gval  = new GValue(this,"Progress",val,0.0,1.0,.01,vflags,this);
    gtext = new GText(this,"",text,aw,ah,0,this);
    addTo (parent);
  }

  /**
    * Sets a new value for the progress bar and updates the display.
    * @param value the new value
    */
  public void setProgress (double value) {
    if (Math.abs(value-val)<0.01) return;
    val = value;
    gval.setValue(val);
  }

  /**
     Processes dialog messages.
     @param msg {@inheritDoc}
     @return 1 if dialog message sent, 0 otherwise
   */
  @Override
  public int processMessage (Message msg) {
    if (msg.name.equals("DIALOG")) {
      sendWidgetMessage(label,0,msg.data);
      if (!is(PERM) && msg.data.equals("EXIT")) close();
      return 1;
    }
    return 0;
  }
}
