import java.awt.*;
import java.awt.event.*;
import javax.swing.*; 

public class ThreadDemo extends JFrame implements Runnable, ActionListener {

    public final static int MAX = 100;
    public final static int SLEEP = 1000;
    private JProgressBar progressBar = null;
    private int count = MAX;
    private JButton startButton = null;
    private Thread thread = null;
    private VarmintDB varmintDB = null;;

    public ThreadDemo(VarmintDB varmintDB_) {
	
	super("ThreadDemo");

	varmintDB = varmintDB_;
	
	progressBar = new JProgressBar(0, MAX);
	progressBar.setValue(0);
	progressBar.setStringPainted(true);
	
	startButton = new JButton("reset");
	JPanel panel = new JPanel();
	
	startButton.addActionListener(this);

	panel.add(progressBar);
	panel.add(startButton);
	
	setContentPane(panel);
	
    }

    public void actionPerformed(ActionEvent e) {
	
	doAction();
    }
    
    // dummy connect and disconnect methods
    //
    public void connect() { }
    public void disconnect() { }

    // perform some action
    //
    public void doAction() {
	
	if (thread == null) {
	    //	    System.out.println("timed out, must restart (reconnect)");
	    connect();

	    // reconnect the database
	    //
	    varmintDB.connect();

	    // restart thread
	    //
	    thread = new Thread(this, "Tester");
	    thread.start();
	}

	// reset counters
	//
	count = MAX;
	progressBar.setValue(count);
    }
    public void run() {
	while (true) {
	    try {
		thread.sleep(SLEEP);
	    } catch (InterruptedException e) { }
	    
	    count--;
	    
	    if (count >= 0) {
		progressBar.setValue(count);
	    } 
	    else {

		varmintDB.disconnect();
		thread = null;
		disconnect();
		return;
	    }
	}
    }
}
