import java.lang.*;
import java.util.*;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.bluetooth.*;
public class DiscoveryMIDlet extends MIDlet implements
       CommandListener, DiscoveryListener {
    public Display display;
    public Form form;
    public Command cancel;
    public Command connect,backtolist;
    public Command back;
    public Command exit;
    public List remotedev;
    public List blue;
     public List applist;
    public  List serviceRecordList;
    public Alert alert;
    public int i;
    public String connectionURL= null;
     public String hhh;
     public boolean close;
    public StreamConnection conn;
    public InputStream input;
   DataOutputStream dout;
   DataInputStream din;
    public LocalDevice local=null;
    private Vector devicesFound = null;
    private ServiceRecord[] servicesFound = null;
    private Vector serviceFound = null;
          /** The DiscoveryAgent for the local device. */
    public DiscoveryAgent agent;
    /** Retrieves the list of pre-known and cached devices.
     * Updates the display to show the list of devices.   */
    public void startApp()    {
        display = Display.getDisplay(this);
        form = new Form("Seaching...");
        blue = new List("Mobile Remote Control",List.IMPLICIT);
        blue.append("Search", null);
        blue.append("Help", null);
        
        serviceRecordList = new List("Services Found",List.IMPLICIT);
        applist= new List("Mobile Remote Control",List.IMPLICIT);
       applist.append("Mouse controller", null);
       applist.append("Keyboard controller", null);
        backtolist= new Command("backtolist", Command.OK, 0);
        back = new Command("Back", Command.BACK, 2);
       
        
        exit = new Command("Exit", Command.EXIT, 1);
        cancel = new Command("Cancel", Command.CANCEL, 1);
        connect = new Command("connect", Command.OK, 3);
       
        serviceRecordList.setCommandListener(this);
        serviceRecordList.addCommand(connect);
        serviceRecordList.addCommand(backtolist);
       //  serviceRecordList.setSelectCommand(connect);

       form.addCommand(cancel);
        form.setCommandListener(this);
        
       applist.addCommand(backtolist);
       applist.setCommandListener(this);
        blue.addCommand(exit);
        blue.setCommandListener(this);
        Display.getDisplay(this).setCurrent(blue);
        close = false;
// Retrieve the DiscoveryAgent object. If
// retrieving the local device causes a
// BluetoothStateException, something is wrong
// so stop the app from running.
        try {
            LocalDevice local = LocalDevice.getLocalDevice();
            agent = local.getDiscoveryAgent();
              } catch (BluetoothStateException bse) {
            // Error handling code here
            }

           }
     public void doDeviceDiscovery() {
           remotedev = new List("List of Devices", List.IMPLICIT);
          remotedev.addCommand(back);
          remotedev.setCommandListener(this);
            devicesFound = new Vector();
            try {
            if (!agent.startInquiry(DiscoveryAgent.GIAC, this)) {
            // Inquiry not started, error handling code here
            }
            } catch (BluetoothStateException bse) {
            // Error handling code here
            }
      }
    public void deviceDiscovered(RemoteDevice device, DeviceClass cod) {
       String name = null;
       int classofdev;
       String address = device.getBluetoothAddress();
       classofdev = cod.getMajorDeviceClass();
       try {
       name = device.getFriendlyName(true);
       } catch (Exception e) {
       }
       if (name == null) {
       name = address;
       }
       if (classofdev == 256) {
       remotedev.append(name, null);
       devicesFound.addElement(device);
       display.setCurrent(remotedev);
        }
        }
 public void inquiryCompleted(int type) {
       switch (type) {
       case DiscoveryListener.INQUIRY_COMPLETED:
       /* Inquiry completed normally, add appropriate code here  */
       if (devicesFound.size() == 0) {
       try {
       remotedev.append("No Devices Found", null);
       display.setCurrent(remotedev);
       } catch (Exception e) {
       }
       }
       break;
       case DiscoveryListener.INQUIRY_ERROR:
       // Error during inquiry, add appropriate code here.
       break;
       case DiscoveryListener.INQUIRY_TERMINATED:
   /* Inquiry terminated by agent.cancelInquiry() Add appropriate code here. */
       break;
       }
       }
    public void connecttodevice() {
 try{
 StreamConnection conn = (StreamConnection) Connector.open(connectionURL);
 dout = new DataOutputStream(conn.openOutputStream());//Get the output stream
        din = new DataInputStream(conn.openInputStream());
 // send msg to server=write
 String msg = " hello this is my first msg  ";
 dout.write(msg.getBytes());
 dout.flush();
// output.close();
  // conn.close();
 // recive msg from server= read
 ByteArrayOutputStream out = new ByteArrayOutputStream();
int data;
while ((data = input.read()) != -1) {
out.write(data);
 }
String bms =out.toString();
serviceRecordList.append(bms, null);
//display.setCurrent(serviceRecordList);
}catch (Exception e) {
      }}
     private void doServiceSearch(RemoteDevice device) {
      int[] attributes = {0x100, 0x101, 0x102};
      UUID[] uuids = new UUID[1];
      uuids[0] = new UUID(0x1101);
      try {
      agent.searchServices(null, uuids, device, this);
      } catch (BluetoothStateException e) {
      Alert alert1 = new Alert("Error");
      alert1.setString(e.toString());
      display.setCurrent(alert1);
      }
      }
     public void servicesDiscovered(int transID,ServiceRecord[] record) {
     for (int i = 0; i < record.length; i++) {
   String   m_strUrl = record[i].getConnectionURL(ServiceRecord.
         NOAUTHENTICATE_NOENCRYPT, false);
     }
     connectionURL= record[0].getConnectionURL(ServiceRecord.
     NOAUTHENTICATE_NOENCRYPT, false);
     }
    public void serviceSearchCompleted(int transID, int type) {
        switch (type) {
        case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
            connecttodevice();
        break;
        case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
        break;
        case DiscoveryListener.SERVICE_SEARCH_ERROR:
        break;
        case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
        break;
        case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
        break;
        }    }
  /* Called when a Command is selected. If it is an */
    public void commandAction(Command c, Displayable d) {
        if (d==blue) {
            if (c==blue.SELECT_COMMAND){
               String selection = blue.getString(blue.getSelectedIndex());
               if (selection.equals("Search")){
              display.setCurrent(form);
              doDeviceDiscovery();
               }
               else if(selection.equals("Help"))
               {
              alert = new Alert("Mobile Remote Control", "Mobile Remote Control is universal PC" +
                      " remote control Search : look for computers to connect"
                      , null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.INFO);
display.setCurrent(alert); }
}
        else if (c== exit ){
    //     destroyApp(true);
         notifyDestroyed();
            }
            }
          if (c == cancel && d ==form) {
// Try to cancel the inquiry.
         agent.cancelInquiry(this);
         display.setCurrent(blue);
        }
        if (c == back && d ==remotedev) {

       display.setCurrent(blue);
       }
        if (c == remotedev.SELECT_COMMAND && d ==remotedev) {
        int device = remotedev.getSelectedIndex();
       // String selection = remotedev.getString(remotedev.getSelectedIndex());
        doServiceSearch((RemoteDevice) devicesFound.elementAt(device));
        display.setCurrent(applist);}
        if (d==applist) {
            if (c==applist.SELECT_COMMAND){
               String selection = applist.getString(applist.getSelectedIndex());
               if (selection.equals("Mouse controller")){
              Mousecontroller();
               connecttodevice() ;
                            }
               else if(selection.equals("Keyboard controller"))
               {
              alert = new Alert("Mobile Remote Control", "Mobile Remote Control is universal PC" +
                      " remote control Search : look for computers to connect"
                      , null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.INFO);
display.setCurrent(alert); }
}
                   }
        
        }
     public void Mousecontroller() {

     }
public void pauseApp() {
}
public void destroyApp(boolean unconditional)
    throws MIDletStateChangeException
{
if (unconditional == false)
{
throw new MIDletStateChangeException();
}

}}