package example.bluetooth.demo;
import java.util.TimerTask;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DiscoveryAgent;
public class DemoMIDlet extends MIDlet implements CommandListener,
        DiscoveryListener
{
    private Display display;
    /**
     * For displaying found devices.
     */
    private List listDev;
    private Command cmdExit;
    private Command cmdDiscover;
    private Command cmdUpdateDiscover;
    private Hashtable bluetoothDevices = new Hashtable();
    private LocalDevice devLocal;
    private DiscoveryAgent discoverAgent;


    /**
     * Constructor. Constructs the object and initializes displayables.
     */
    public DemoMIDlet() {
        InitializeComponents();
    }
    /**
     * Initializes a ListBox object and adds softkeys.
     */
    protected void InitializeComponents() {
        display = Display.getDisplay( this );
        //initializing device list
        listDev = new List( "Device list", List.IMPLICIT );

        cmdExit = new Command( "Exit", Command.EXIT, 1 );
        cmdDiscover = new Command( "Start", Command.SCREEN, 1);
       cmdUpdateDiscover = new Command( "Update", Command.SCREEN, 1);

        listDev.addCommand( cmdExit );
        listDev.addCommand( cmdDiscover );
        listDev.setCommandListener( this );
    }

    /**
     * From MIDlet.
     * Called when MIDlet is started.
     * @throws javax.microedition.midlet.MIDletStateChangeException
     */
    public void startApp() throws MIDletStateChangeException {
        display.setCurrent( listDev );
    }
    /**
     * From MIDlet.
     * Called to signal the MIDlet to enter the Paused state.
     */
    public void pauseApp() {
        //No implementation required
    }
    /**
     * From MIDlet.
     * Called to signal the MIDlet to terminate.
     * @param unconditional whether the MIDlet has to be unconditionally
     * terminated
     * @throws javax.microedition.midlet.MIDletStateChangeException
     */
    public void destroyApp(boolean unconditional) throws MIDletStateChangeException {
        exitMIDlet();
    }
    /**
     * From CommandListener.
     * Called by the system to indicate that a command has been invoked on a
     * particular displayable.
     * @param command the command that was invoked
     * @param displayable the displayable where the command was invoked
     */

    public void commandAction( Command command, Displayable displayable ) {

        if( command == cmdExit ) {
            exitMIDlet();
        }
        if( command == cmdDiscover ) {
            int err = 0;
            err = initLocalDevice();
            if( err != 0 ){
                return;
            }
            err = startDeviceSearch();
            if( err != 0) {
                return;
            }

            //we do not need a start soft key when in descovery mode
            listDev.removeCommand( cmdDiscover );
            //now we add stop soft key
            listDev.addCommand( cmdUpdateDiscover );
        }
       if( command == cmdUpdateDiscover ) {
           UpdateDiscover();
              listDev.deleteAll();
        bluetoothDevices.clear();
            //we remove stop softkey
            listDev.removeCommand( cmdUpdateDiscover );
            //adding start soft key
            listDev.addCommand( cmdDiscover );
        }
    }


    /**
     * Method calls stopDiscover method and notifyDestroyed after that.
     */
    protected void exitMIDlet()
    {
        UpdateDiscover();
        notifyDestroyed();
    }
    /**
     * Gets a reference to LocalDevice and saves it to devLocal variable.
     * @return 0 if local device reference getting succeded. -1 on exception.
     */
    protected int initLocalDevice() {
        try {
            devLocal = LocalDevice.getLocalDevice();
        } catch (BluetoothStateException e) {
            showErrAlert( "Error getting local device!" );
            return -1;
        }
        return 0;
    }
    /**
     * Clears device listbox, retreves DiscoveryAgent instance and saves it to
     * discoveryAgent variable. Starts device inquiry mode with access code
     * General/Unlimited Inquiry Access Code (GIAC).
     * @return 0 function execution was successfull.
     * -1 if startInquiry threw an exception.
     * @see JSR82 for more info.
     */
    protected int startDeviceSearch() {
        discoverAgent = devLocal.getDiscoveryAgent();
        try {

            discoverAgent.startInquiry( DiscoveryAgent.GIAC,
                    this );
        } catch( BluetoothStateException e ) {
            showErrAlert( "Error starting device enquiry!" +e);
            return -1;
        }
        return 0;
    }

    /**
     * From DiscoveryListener.
     * Called when new bluetooth device discovered.
     * @param remoteDev reference to RemoteDevice object instance of
     * discovered device
     * @param devClass the service classes, major device class,
     * and minor device class of the remote device
     */
    public void deviceDiscovered(RemoteDevice remoteDev, DeviceClass devClass) {
        try {
            System.out.println("deviceDisc: " + remoteDev.getFriendlyName(false));
            // Add Device to table
            bluetoothDevices.put(remoteDev.getFriendlyName(false), remoteDev);
			bluetoothCopyDeviceTableToList();


        } catch (Exception e) {
            System.out.println("Exception (b4): " + e);
        }
    }

    /**
     * From DiscoveryListener.
     * Called when service(s) are found during a service search.
     * @param transID the transaction ID of the service search that is
     * posting the result
     * @param servRecord a list of services found during the search request
     */
    public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
        //No implementation required
    }

    /**
     * From DiscoveryListener.
     * Called when a service search is completed or was terminated
     * because of an error
     * @param transID the transaction ID identifying the request which
     * initiated the service search
     * @param respCode the response code that indicates the status
     * of the transaction
     */
    public void serviceSearchCompleted(int transID, int respCode) {
        //No implementation required
    }

    /**
     * From DiscoveryListener.
     * Called when an inquiry is completed.
     * @param discType the type of request that was completed
     */
    public void inquiryCompleted(int discType) {

    }
    /**
     * Show error alert with a string specified in strError.
     * @param strError Error message show.
     */
    protected void showErrAlert( String strError ) {
        Alert alertErr = new Alert("Error", strError, null, AlertType.ERROR );
        display.setCurrent( alertErr );
    }

    /**
     * Stops device discovery mode.
     */
    protected void UpdateDiscover() {
        discoverAgent.cancelInquiry(this);


    }
	private void bluetoothCopyDeviceTableToList() { // copies the discovered bluetooth devices to a list and also displays the result
        String sensors[]=new String[4];
        int len=0;
        String sens[]=new String[4]; // declaration and initialization of 4 sensors
                sens[0]="GEVARA";
                sens[1]="IMETRIX-PC";
                sens[2]="Naif";
                sens[3]="NOONY";
           int res[]=new int[4]; // this is used to store the results ..integere value 0 is sensor not detected 1 is detected
           for(int p=0;p<4;p++)
           {
                 res[p]=0;
           }


        listDev.deleteAll();
        // Append keys from table
        for (Enumeration e = bluetoothDevices.keys(); e.hasMoreElements(); ) {

            try {
                String name = (String) e.nextElement();
                sensors[len]=name.trim();
                listDev.append( sensors[len], null );// write it here and replace k with len for all the bluetooth devices discoverable
                len++;

            } catch (Exception exception) {
                System.out.println(""+exception);
            }
        }

            for(int k=0;k<len;k++) //discovery of sensors
            {
                for(int l=0;l<4;l++){
                 if(sensors[k].equals(sens[l])){
                     res[l]=1;
                 }
                }
            }

           String str1="-----------SMS-----------";
           listDev.append(str1, null);
           if(res[0]==1 && res[1]==0 && res[2]==0 && res[3]==0) // if ladder to identify the zones, it is done accordin to the sensors detection at a given place
                listDev.append( "You are in Zone1", null );
            if(res[0]==1 && res[1]==1 && res[2]==0 && res[3]==0)
                listDev.append( "You are in Zone2", null );
           if(res[0]==0 && res[1]==1 && res[2]==0 && res[3]==0)
                listDev.append( "You are in Zone3", null );
           if(res[0]==0 && res[1]==1 && res[2]==1 && res[3]==0)
                listDev.append( "You are in Zone4", null );
           if(res[0]==1 && res[1]==1 && res[2]==1 && res[3]==0)
                listDev.append( "You are in Zone5", null );
           if(res[0]==1 && res[1]==1 && res[2]==0 && res[3]==1)
                listDev.append( "You are in Zone6", null );
           if(res[0]==1 && res[1]==0 && res[2]==0 && res[3]==1)
                listDev.append( "You are in Zone7", null );
           if(res[0]==1 && res[1]==1 && res[2]==1 && res[3]==1)
                listDev.append( "You are in Zone8", null );
           if(res[0]==0 && res[1]==1 && res[2]==1 && res[3]==1)
                listDev.append( "You are in Zone9", null );
           if(res[0]==1 && res[1]==0 && res[2]==1 && res[3]==1)
                listDev.append( "You are in Zone10", null );
           if(res[0]==0 && res[1]==0 && res[2]==1 && res[3]==0)
                listDev.append( "You are in Zone11", null );
           if(res[0]==0 && res[1]==0 && res[2]==1 && res[3]==1)
                listDev.append( "You are in Zone12", null );
           if(res[0]==0 && res[1]==0 && res[2]==0 && res[3]==1)
                listDev.append( "You are in Zone13", null );
        for(int t=0;t<len;t++)
        {
            sensors[len]="";
        }
         for(int p=0;p<4;p++)
           {
               res[p]=0;
           }
        len=0;
     
    }
    }


