package sms;

import java.io.IOException;
import java.util.Vector;
import javax.bluetooth.*;

/**
 * Trieda pre najdenie zariadenia
 * @author Richard Scepko
 */
public class DeviceDiscovery {

    /**
     * Vektor najdenych zariadeni
     */
    public Vector devicesDiscovered = new Vector();

    public DeviceDiscovery() throws BluetoothStateException{

    }

    /**
     * Hlada zariadenia
     * @throws BluetoothStateException
     * @throws InterruptedException
     */
    public void run() throws BluetoothStateException, InterruptedException{
        devicesDiscovered = new Vector();

        final Object inquiryCompletedEvent = new Object();

        devicesDiscovered.clear();

        DiscoveryListener listener = new DiscoveryListener() {

            /**
             * vnutorna metoda pre najdenie jedneho zariadenia
             */
            public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
                System.out.println("Device " + btDevice.getBluetoothAddress() + " found");
                devicesDiscovered.addElement(btDevice); //pridame zariadenie
                try {
                    System.out.println("     name " + btDevice.getFriendlyName(false));
                } catch (IOException cantGetDeviceName) {
                }
            }

            /**
             * Vnutorna metoda pre dokoncenie hladania
             */
            public void inquiryCompleted(int discType) {
                System.out.println("Device Inquiry completed!");
                synchronized(inquiryCompletedEvent){
                    inquiryCompletedEvent.notifyAll();
                }
            }

            public void serviceSearchCompleted(int transID, int respCode) {
            }

            public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
            }
        };

        synchronized(inquiryCompletedEvent) {
            boolean started = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, listener);
            if (started) {
                System.out.println("wait for device inquiry to complete...");
                inquiryCompletedEvent.wait();
                System.out.println(devicesDiscovered.size() +  " device(s) found");
            }
        }
    }

}
