package progressbar;

import org.gnu.gtk.Alignment;
import org.gnu.gtk.Button;
import org.gnu.gtk.CheckButton;
import org.gnu.gtk.Gtk;
import org.gnu.gtk.HSeparator;
import org.gnu.gtk.ProgressBar;
import org.gnu.gtk.VBox;
import org.gnu.gtk.Window;
import org.gnu.gtk.WindowType;
import org.gnu.gtk.event.ButtonEvent;
import org.gnu.gtk.event.ButtonListener;
import org.gnu.gtk.event.LifeCycleEvent;
import org.gnu.gtk.event.LifeCycleListener;
import org.gnu.glib.Timer;
import org.gnu.glib.Fireable;

public class ProgressBarTest implements Fireable {

	private ProgressBar progressbar = null;
	private Timer timer = null;

	public ProgressBarTest() {

		Window window = new Window(WindowType.TOPLEVEL);
		window.setBorderWidth(0);
		window.setTitle("ProgressBar Example");
		window.addListener(new LifeCycleListener() {
			public void lifeCycleEvent(LifeCycleEvent event) {}
			public boolean lifeCycleQuery(LifeCycleEvent event) {
				if (event.isOfType(LifeCycleEvent.Type.DESTROY) || 
						event.isOfType(LifeCycleEvent.Type.DELETE)) {
						Gtk.mainQuit();
				}
				return false;
			}
		});

		VBox vbox = new VBox(false, 5);
		vbox.setBorderWidth(10);
		window.add(vbox);

		/* Create a centering alignment object */
		Alignment align = new Alignment(0.5, 0.5, 0, 0);
		vbox.packStart(align, false, false, 5);

		/* Create the ProgressBar using the adjustment */
		progressbar = new ProgressBar();

		align.add(progressbar);

		HSeparator hsep = new HSeparator();
		vbox.packStart(hsep, false, false, 0);

		/* Add a button to exit the program */
		Button button = new Button("close");
		button.addListener(new ButtonListener() {
			public void buttonEvent(ButtonEvent event) {
				if (event.isOfType(ButtonEvent.Type.CLICK)) {
					exitProgram();
				}
			}
		});
		vbox.packStart(button, false, false, 0);

		window.showAll();

		timer = new Timer(100, this);
		timer.start();
	}

	public boolean fire(){
		double percent = progressbar.getFraction();
		if (percent >= .99)
			percent = 0.0;
		else {
			percent += 0.01;
			if (percent >= 1.0)
				percent = .999;
		}
		progressbar.setFraction(percent);
		return true;
	}

	public void exitProgram() {
		/* First stop the timer */
		timer.stop();
		/* Now stop the event loop and exit GTK */
		Gtk.mainQuit();
	}

	public static void main(String[] args) {
		// Initialize GTK 
		Gtk.init(args);

		ProgressBarTest pb = new ProgressBarTest();

		Gtk.main();
	}
}
