package pddemo;

import com.ibm.aglet.*;
import com.ibm.aglet.event.*;
import java.net.URL;
import java.io.IOException;

public class DispatchDeactive 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("I will deactivate for 5 seconds");
         
        	try {
                     deactivate(5*1000);
               	} catch(IOException de) {   
                     de.printStackTrace();
               	}
   
        	print("I am active again");

		dispose();

            }
         }
      );
   }

   public void run() {
      if (!_theRemote) {
         print("STARTING");
         print("\'run()\' is starting...");
         pause();
         try {
            print("Dispatching itself...");
            String host = getAgletContext().getHostingURL().toString();
			String dest = "atp://cx9108458:500/"; // change
            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...");
         
        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) { } }
}
