package pddemo;

import com.ibm.aglet.*;
import com.ibm.aglet.event.*;
import java.net.URL;

public class DispatchingExample extends Aglet {

   boolean _theRemote = false;

   public void onCreation(Object o) {
      addMobilityListener(
   	 new MobilityAdapter() {
	    public void onDispatching(MobilityEvent e) {
	       print("\'onDispatching()\' is starting...");
               print("\'onDispatching()\': Destination is \'" + e.getLocation() + "\'");
               pause();
               print("\'onDispatching()\' is finishing.");
            }
	    public void onArrival(MobilityEvent e) {
               _theRemote = true;  //-- Yes, I am the remote aglet.
               print("\'onArrival()\' is starting...");
               pause();
               print("\'onArrival()\' is finishing.");
            }
         }
      );
   }

   public void run() {
      if (!_theRemote) {
         print("STARTING");
         print("\'run()\' is starting...");
         pause();
         try {
            print("Dispatching itself...");
            String host = getAgletContext().getHostingURL().toString();
            setText(host);
			String dest = "atp://cx9108449:434/"; // change 
			//clone();
            URL destination = new URL (dest);
            print("Destination is \'" + destination.toString() + "\'");
            dispatch(destination);
            print("You should never see this on your console!");
         } catch (Exception e) {
            print("Failed to dispatch itself.");
            print(e.getMessage());
         }
         pause(); pause();
         print("\'run()\' is finishing.");
      } else {
         print("\'run()\' is starting...");
         pause();
         print("\'run()\' is finishing.");
      }
   }

   void print(String s) { System.out.println("Dispatching" + (_theRemote ? "   (remote): " : " (original): ") + s); }
   private static long SLEEP = 3000;
   void pause() { try { Thread.sleep(SLEEP); } catch (InterruptedException ie) { } }
}
