   package net.benhui.btgallery.spp_bt;

   import javax.microedition.lcdui.*;
   import javax.bluetooth.*;
   import javax.microedition.io.*;
   import java.io.*;
   import net.benhui.btgallery.*;
   import net.benhui.btgallery.spp_gui.*;

/**
 *
 * <p>Title: Example Serial Port Profile Server.</p>
 * <p>Description: This example server only handle one SPP server connection
 * and wait for a client to connect. Once a client connection accept, it read
 * one string off the connection stream, display this string on screen, then
 * echo the string back to client.
 * Then it waits for the next client connection again.</p>
 * <p>Description: Important area: run() </p>
*
 * @author Ben Hui (www.benhui.net)
 * @version 1.0
 *
 * LICENSE:
 * This code is licensed under GPL. (See http://www.gnu.org/copyleft/gpl.html)
 */
    public class SPP_Server
   {
   // Bluetooth singleton object
      LocalDevice device;
      DiscoveryAgent agent;
   
   // SPP_Server specific service UUID
   // note: this UUID must be a string of 32 char
   // do not use the 0x???? constructor because it won't
   // work. not sure if it is a N6600 bug or not      
      public final static UUID uuid3= new UUID("102030405060708090A0B0C0D0E0F011", false);
		public final static UUID uuid2 = new UUID("102030405060708090A0B0C0D0E0F010", false);
      public final static UUID uuid = new UUID("102030405060708090A0B0C0D0E0F012", false);
   
   //
   // major service class as SERVICE_TELEPHONY
        
   
   // control flag for run loop
   // set true to exit loop
      public boolean done = false;
   
   // our BT server connection
      public StreamConnectionNotifier server;
      public StreamConnectionNotifier server2;
      public StreamConnectionNotifier server3;
   
       public SPP_Server()
      {
      }
   
       public void run_server()
      {
         try
         {
         //
         // initialize the JABWT stack
            device = LocalDevice.getLocalDevice(); // obtain reference to singleton
            device.setDiscoverable(DiscoveryAgent.GIAC); // set Discover mode to LIAC
            new ThreadedWaiting (device,uuid,"SPPServerExample1",100,this).start();
				new ThreadedWaiting (device,uuid2,"SPPServerExample2",1,this).start();
            new ThreadedWaiting (device,uuid3,"SPPServerExample3",20,this).start();

            
         } 
             catch ( BluetoothStateException e )
            {
               e.printStackTrace();
            }
      
      }
       public void log( String s )
      {
         SPP_MIDlet.log( s );
      }
   }

    class ThreadedWaiting extends Thread
   {
 
		 public ThreadedWaiting(LocalDevice device, UUID uuid, String appName, int incrementa, SPP_Server spp_servidor) {
		     this.device = device;
			  this.uuid = uuid;
			  this.appName = appName;
			  this.incrementa = incrementa;
			  this.spp_servidor = spp_servidor;
		 }
       public void run()
       { 
		      StreamConnection c = null;
         try
         {
       //     String appName = "SPPServerExample1";
       //     String appName2 = "SPPServerExample2";
       //     String appName3 = "SPPServerExample3";
            String url = "btspp://localhost:" + uuid.toString() +";name="+ appName;
       //     String url2 = "btspp://localhost:" + uuid2.toString() +";name="+ appName2;
       //     String url1 = "btspp://localhost:" + uuid3.toString() +";name="+ appName3;
            log("server url: " + url );
           // log("server url: " + url2 );
    //        log("server url: " + url3 );
         
         // Create a server connection object, using a
         // Serial Port Profile URL syntax and our specific UUID
         // and set the service name to BlueChatApp
          //  server2 =  (StreamConnectionNotifier)Connector.open( url2 );
            server =  (StreamConnectionNotifier)Connector.open( url );
   //         server3 =  (StreamConnectionNotifier)Connector.open( url3 );
         
         // Retrieve the service record template
            ServiceRecord rec = device.getRecord( server );
   //         ServiceRecord rec = device.getRecord( server2 );
     //      ServiceRecord rec3 = device.getRecord( server3 );
         
         // set ServiceRecrod ServiceAvailability (0x0008) attribute to indicate our service is available
         // 0xFF indicate fully available status
         // This operation is optional
           // rec2.setAttributeValue( 0x0008, new DataElement( DataElement.U_INT_1, 0xFF ) );
            rec.setAttributeValue( 0x0008, new DataElement( DataElement.U_INT_1, 0xFF ) );
     //       rec3.setAttributeValue( 0x0008, new DataElement( DataElement.U_INT_1, 0xFF ) );
         
         // Print the service record, which already contains
         // some default values
			   log("server2 ..." + appName);
            Util.printServiceRecord( rec );
			//	log("server");
          //  Util.printServiceRecord( rec2 );
      //      Util.printServiceRecord( rec3 );
         
         // Set the Major Service Classes flag in Bluetooth stack.
         // We choose Telephony Service
     //       rec2.setDeviceServiceClasses( SERVICE_TELEPHONY  );
            rec.setDeviceServiceClasses( SERVICE_TELEPHONY  );
      //      rec3.setDeviceServiceClasses( SERVICE_TELEPHONY  );
         
         
         
         } 
             catch (Exception e)
            {
               e.printStackTrace();
               log(e.getClass().getName()+" "+e.getMessage());
            }
//            new ThreadedSending(server2,200).start();				
//			   new ThreadedSending(server,10).start();

		 log("Ingresando a run Hebra ...");
		       // connection to remote device
      	      //		new ThreadedSending(server3,100).start();
         while(true) {
            try {
               c = server.acceptAndOpen();
            
            // start a thread to serve the server connection.
            // for simplicity of this demo, we only start one server thread
            // see run() for the task of this thread
               new ThreadedSending(c, server, incrementa ).start();
            }
                catch(Exception e) {
                  e.printStackTrace();
                  SPP_MIDlet.alert(e, SPP_MIDlet.instance.spp_screen );
               }
         }
/*
		 try {
		  c = server.acceptAndOpen();
		  	}
        catch(Exception e) {
                  e.printStackTrace();
                  SPP_MIDlet.alert(e, SPP_MIDlet.instance.spp_screen );
        }
*/

      // human friendly name of this service
      
      }
		  /**
   * An utility function to display a log message
   * @param s String
   */

       public void log( String s )
      {
         SPP_MIDlet.log( s );
      }
   
      StreamConnection c = null;
      StreamConnectionNotifier server = null;
		LocalDevice device = null;
		UUID uuid = null;
		String appName = null;
   	int incrementa;
		 private final static int SERVICE_TELEPHONY = 0x400000;
		 SPP_Server spp_servidor;

   }
class ThreadedSending extends Thread
   {
       public ThreadedSending( StreamConnection c, StreamConnectionNotifier serv, int increment) {
       
         this.c = c;     
         server = serv;
      	incrementa = increment;
       }
		 public void run(){
		           boolean done = false;
         while( !done)
         {
            try {
            ///////////////////////////////
               log("local service waiting for client connection...");
               boolean flag = true;
            //
            // start accepting client connection.
            // This method will block until a client
            // connected
            
               log("accepted a client connection. reading it...");
            //
            // retrieve the remote device object
               RemoteDevice rdev = RemoteDevice.getRemoteDevice( c );
            
            // obtain an input stream to the remote service
               DataInputStream in = c.openDataInputStream();
               DataOutputStream out = c.openDataOutputStream();
            
               while (flag) {
               // read in a string from the string
                  String s = in.readUTF();
                  int i = Integer.parseInt(s);
                  System.out.println(i);
                  log("read in data '"+s+"' from client");
                  i = i + incrementa;
                  s = String.valueOf(i);
                  out.writeUTF( s );
                  out.flush();
               
                  log("echo '"+s+"' back to client");
               }
               in.close();
               out.close();
            
            
            // close current connection, wait for the next one
               c.close();
            
            
            } 
                catch (Exception e)
               {
                  e.printStackTrace();
                  SPP_MIDlet.alert(e, SPP_MIDlet.instance.spp_screen );
               }
         
         } // while

		 
		 }
		  /**
   * An utility function to display a log message
   * @param s String
   */

       public void log( String s )
      {
         SPP_MIDlet.log( s );
      }
		 
      StreamConnectionNotifier server = null;
		   StreamConnection c = null;
		   int incrementa;

	}	 