/*
 * 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.*;
import  java.io.*;

/**
 * put your documentation comment here
 */
public class Client extends Aglet 
{
	AgletProxy proxy;
	boolean theRemote = false;
	String host = "localhost:4444";
	int noOfRequest = 50000;
	int fileNameBound = 1000;

    int waitUpperBound = 10;
	int waitMean = waitUpperBound/2;
	double waitSTD = (waitUpperBound * 0.99 - waitMean)/3;

    // parameter for the server    
    String algorithm = null;    // replacement algorithm
	Integer mainBufferSize = null;  
	Long modifyPeriod = null;   // aux size modification period	
    Boolean isFixFileSize = null;
	
	/**
	 * 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;
				}
			}
		);        
        
        // initialize server side parameter
        algorithm = "PureLRU";
        mainBufferSize = new Integer(100000);  
        modifyPeriod = new Long(1000);
        isFixFileSize = new Boolean(true);



	}

	/**
	 * put your documentation comment here
	 */
	public void run () 
	{
        // test only
        /*
        try {
        	Thread.sleep(4000);
        }
        catch (Exception e) {
        }        
        */

		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);
						wait( (long)(requestTime)+1 );

					}
				}
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}
		}
		else
		{
			try 
			{
                Object[] init = new Object[] {algorithm, mainBufferSize, modifyPeriod, isFixFileSize};

				proxy = getAgletContext().createAglet(getCodeBase(), "project.Server", init);
				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);
	}
}



