package extras;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Handler;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

import controllers.PinpadManager;
import models.messaging.nibss.Globals;

/**
 * Created by RASAQ PC on 30/09/15.
 */
public class BluetoothList {

    private JSONObject bluetoothList;

    private class BluetoothDevicePair {
        String name;
        String addr;
    }

//    public JSONObject connect(){
//        mPinpadManager = PinpadManager.getInstance(this);
//        deviceActivityHandler = new Handler();
//        mPinpadManager
//                .setOnConnectionEstablishedListener(new PinpadManager.OnConnectionEstablishedListener() {
//                    @Override
//                    public void OnConnectionEstablished() {
//
//                        runOnUiThread(new Runnable() {
//                            public void run() {
//                                // set this to check if connected
//                                Globals.isPinpadConnected = true;
//
//                                //showToast(getString(R.string.msg_pinpad_connected));
//                                setResult(RESULT_OK);
//                                finish();
//                            }
//                        });
//                    }
//                });
//
//    }

    public JSONObject updateDeviceList() {


        BluetoothAdapter bthAdapter = BluetoothAdapter.getDefaultAdapter();
        JSONObject deviceJS = new JSONObject();

        if (bthAdapter != null) {

            if (bthAdapter.isEnabled()) {

                try {
                    if (bthAdapter != null) {

                        JSONArray array = new JSONArray();
                        for (BluetoothDevice device : bthAdapter.getBondedDevices()) {
                            BluetoothDevicePair pair = new BluetoothDevicePair();
                            pair.name = device.getName();
                            pair.addr = device.getAddress();
                            JSONObject deviceJS1 = new JSONObject();
                            deviceJS1.put("name", device.getName());
                            deviceJS1.put("address", device.getAddress());
                            array.put(deviceJS1);
                        }

                        deviceJS.put("devices",array);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }else{
                //to do:open bluetooth-open dialog here or send back to app using json
                
                
            }
        }else{
            //to do:bluetooh not enabled-put stirng in jsonobject
        }

        return deviceJS;


    }
}
