/**
 *
 * @author Copyright (c) 2000 by BEA Systems, Inc. All Rights Reserved.
 */
package examples.applets.ping;

import java.net.*;
import java.io.*;
import java.applet.*;
import java.awt.*;
import weblogic.common.*;

class Pinger implements Runnable {

    TextApplet ap;
    int count;
    Statistics stats;
    String protocol;
    int port;
    Pinger(TextApplet ap, Statistics stats) {
	this.ap = ap;
	this.stats = stats;
    }

    boolean started = false;
    boolean quitAll = false;

    void p(String s) {
	ap.p("ping thread: " +s);
    }

    synchronized void start(String proto, int port) {
	started = true;
	this.port = port;
	protocol = proto;
	notify();
    }

    synchronized void stop() {
	started = false;
	protocol = null;
	notify();
    }

    synchronized void quit() {
	quitAll = true;
	notify();
    }

    private synchronized boolean isRunning() {
	return started;
    }

    public void run() {
	while (true) {
	    try {
		synchronized (this) {
		    while (!isRunning()) {
			p("wait...");
			wait();
			if (quitAll) {
			    p("QUIT ALL: thread exiting..");
			    return;
			}
		    }
		}
		startPinging();
	    } catch (Throwable t) {
		stop();
		p("ERROR: " + t + ", lost connection.");
		t.printStackTrace();
	    }
	}
    }

    void startPinging() throws Exception {
	String url = protocol + "://" + ap.getCodeBase().getHost() + ":"+
	    port + "/";
	p("***connect to URL="+url+":***");
	//	T3Connection t3conn = new T3Connection(url);
	//	t3conn.connect();
	T3Client t3 = new T3Client(url);
	t3.connect();
	int num = 0;
	byte[] buf = new byte[10];
	p("****start pinging****");
	long beg = System.currentTimeMillis();
	long tmp;
	int last = 0;
	while (isRunning()) {
	    if (++num % 5 == 0) {
		p("ping #:" + num);
	    }
	    t3.services.admin().ping(buf);
	    
	    if ((tmp = System.currentTimeMillis() - beg) > 10000) {
		float tot = (float)(num - last);
		float div = (float)(tmp);
		float rate = tot * 60000F/tmp;
		stats.addData(rate);
		beg = System.currentTimeMillis();
		last = num;
	    }
	}
	p("***disconnect:***");
	t3.disconnect();
    }
}

