/*
 * put your module comment here
 * formatted with JxBeauty (c) johann.langhofer@nextra.at
 */


package  project;

import  com.ibm.aglet.*;
import  com.ibm.aglet.event.*;
import  java.net.URL;
import  java.util.*;


/**
 * put your documentation comment here
 */
public class Client extends Aglet 
{
	AgletProxy proxy;
	boolean theRemote = false;
	String host = "localhost:4444";
	int noOfRequest = 100000;
	int fileNameBound = 1000;

    int waitUpperBound = 10;
	int waitMean = waitUpperBound/2;
	double waitSTD = (waitUpperBound * 0.99 - waitMean)/3;
	
	/**
	 * put your documentation comment here
	 * @param o
	 */
	public void onCreation (Object o) 
	{
		addMobilityListener
		(
			new MobilityAdapter()
			{
				public void onDispatching(MobilityEvent e)
				{
					print("on Dispatching");
				}

				public void onArrival(MobilityEvent e)
				{
					theRemote = true;
				}
			}
		);
	}

	/**
	 * put your documentation comment here
	 */
	public void run () 
	{
        
		if (theRemote)
		{
			try
			{
				Random random = new Random();
				synchronized(this)
				{
					for(int i=0; i<noOfRequest; i++)
					{
						String fileName = "file"+(int)(Math.random()*fileNameBound);
						proxy.sendAsyncMessage(new Message("request", fileName));
                        double requestTime = Math.abs(random.nextGaussian() * waitSTD + waitMean);
                        System.out.println(requestTime + "		" +i);
						wait( (long)(requestTime)+1 );

					}
				}
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}
		}
		else
		{
			try 
			{
				proxy = getAgletContext().createAglet(getCodeBase(), "project.Server", null);
				dispatch(new URL("atp://"+host));

			} 
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
	}
	/**
	 * put your documentation comment here
	 * @param s
	 */
	void print (String s) 
	{
		System.out.println((theRemote? "(remote):":"(original):")+s);
	}
}



