// EAGLE Active Badge Client -- monitors serial port for data from badge
// (via JNI calls to functions in serialtojava.c) and sends updates to
// Location Service (a JINI service) 

// includes for JINI
import net.jini.discovery.*;
import net.jini.core.lookup.*;
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;

// include the interface to the C code 
import LocationClient; 

// Listen for a JINI lookup service 
public class LocationClient implements DiscoveryListener {
    protected ServiceTemplate template;
    protected LookupDiscovery disco;
    
    public static void main(String[] argv) {
	   new LocationClient();
	   try {
	     Thread.currentThread().sleep(100000L);
           }
	   catch(java.lang.InterruptedException e) {}
	}
    public LocationClient() {
	    System.setSecurityManager(new RMISecurityManager());
     	    LookupDiscovery discover = null;
	    try {
		  
                  // debug
                  System.out.println("Constructor ");
                  //end debug

               discover = new LookupDiscovery(
		            LookupDiscovery.ALL_GROUPS);
	    }
	    catch(Exception e) 
	        { System.err.println(""+e);
		  System.exit(1);
		}
	
            discover.addDiscoveryListener(this);
     }
		 
     public void discovered(DiscoveryEvent ev) {
         ServiceRegistrar[] newregs = ev.getRegistrars();
         // debug
          System.out.println("entered discovered ");
         // end debug
         Class [] classes = new Class[]{GetPut.class};
		 GetPut o = null;
                 ReadIR ir = new ReadIR(); 
                 String s; 
		 ServiceTemplate template = 
		    new ServiceTemplate(null, classes, null);
		 for (int i=0 ; i<newregs.length ; i++) {
		    ServiceRegistrar r = newregs[i];
		    try {
			  o = (GetPut) r.lookup(template);
		    }
	  	    catch(java.rmi.RemoteException e) {
			   e.printStackTrace();
			   System.exit(2);
		    }
		    if(o == null) {
                       //debug
                       System.out.println("Continuing search ");
                       continue;
                       }
		    try {
			// this is the code to listen for badges 
                         while(true) { 
                           s = ir.getbadge(); 
                           System.out.println("got badge <" + s +">"+ s.length());
			   // code the location of this client in next line
			   // this call sends the update to the Location Server
			   o.isAt(s, "Shop 112");
                        }
                    }
		    catch(java.rmi.RemoteException e) {
			    System.err.println(""+e);
		    }
		  }
        }
        public void discarded(DiscoveryEvent ev) {}
    }
    
    





