package com.share.connect.ble;

import a.b.a.f.g;
import a.b.a.f.h;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattServerCallback;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.AdvertisingSet;
import android.bluetooth.le.AdvertisingSetCallback;
import android.bluetooth.le.AdvertisingSetParameters;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Pair;
import androidx.collection.ArrayMap;
import com.share.connect.ble.DeviceCache;
import com.share.connect.ble.IBluetoothLe;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.json.JSONObject;

public class BluetoothLeService extends Service {
    private static final String F = "BLEService";
    public static final int G = 30000;
    public static final int H = 48;
    private int A;
    private String B;
    private final i C = new i(this, null);
    private final List<BluetoothLeObserver> D = new ArrayList();
    private boolean E = false;

    /* renamed from: a  reason: collision with root package name */
    private BluetoothManager f174a;
    private BluetoothAdapter b;
    private a.b.a.f.g c;
    private BluetoothLeAdvertiser d;
    private BluetoothGattServer e;
    private final k f = new k(this, null);
    private BluetoothGatt g;
    private j h;
    private h i;
    private Handler j;
    private final Runnable k = new a();
    private AdvertisingSetCallback l;
    private g.c m;
    private DeviceCache n;
    private BroadcastReceiver o;
    private final AtomicBoolean p = new AtomicBoolean(false);
    private String q;
    private String r;
    private String s;
    private String t;
    private String u;
    private String v;
    private String w;
    private String x;
    private int y;
    private final AtomicInteger z = new AtomicInteger(0);

    public class a implements Runnable {
        public a() {
        }

        public void run() {
            a.a.a.b.e(BluetoothLeService.F, "Connect timeout, take this as failure.");
            BluetoothLeService.this.C.connectDone();
            BluetoothLeService.this.g();
            BluetoothLeService.this.b((BluetoothLeService) 3, 1);
        }
    }

    public class b extends BroadcastReceiver {

        /* renamed from: a  reason: collision with root package name */
        public final /* synthetic */ int f176a;

        public b(int i) {
            this.f176a = i;
        }

        public void onReceive(Context context, Intent intent) {
            int intExtra = intent.getIntExtra("android.bluetooth.adapter.extra.STATE", 0);
            a.a.a.b.c(BluetoothLeService.F, "Received bluetooth state: " + intExtra);
            if (intExtra == 12) {
                try {
                    BluetoothLeService bluetoothLeService = BluetoothLeService.this;
                    bluetoothLeService.unregisterReceiver(bluetoothLeService.o);
                } catch (RuntimeException unused) {
                }
                if (!BluetoothLeService.this.l()) {
                    int i = this.f176a;
                    if (i > 0) {
                        BluetoothLeService.this.a((BluetoothLeService) (i - 1));
                    } else {
                        BluetoothLeService.this.b((BluetoothLeService) 1, 2);
                    }
                }
            }
        }
    }

    public class c implements DeviceCache.a {
        public c() {
        }

        @Override // com.share.connect.ble.DeviceCache.a
        public void a(DeviceCache.BtDevice btDevice) {
            BluetoothLeService.this.a((BluetoothLeService) true, (boolean) btDevice);
        }

        @Override // com.share.connect.ble.DeviceCache.a
        public void b(DeviceCache.BtDevice btDevice) {
            BluetoothLeService.this.a((BluetoothLeService) false, (boolean) btDevice);
        }
    }

    public class d implements g.c {
        public d() {
        }

        @Override // a.b.a.f.g.c
        public void a(int i) {
            a.a.a.b.b(BluetoothLeService.F, "Start scanning failed with error code: " + i);
            BluetoothLeService.this.b((BluetoothLeService) 2, 1);
        }

        @Override // a.b.a.f.g.c
        public void a(int i, ScanResult scanResult) {
            if (BluetoothLeService.this.n == null) {
                a.a.a.b.e(BluetoothLeService.F, "onScanResult invoked when mDeviceCache is null.");
            } else if (i == 1) {
                BluetoothLeService.this.n.c(scanResult);
            } else if (i == 0) {
                BluetoothLeService.this.n.b(scanResult);
            }
        }
    }

    public class e implements l {

        /* renamed from: a  reason: collision with root package name */
        public final /* synthetic */ String f178a;

        public e(String str) {
            this.f178a = str;
        }

        @Override // com.share.connect.ble.BluetoothLeService.l
        public void a() {
            BluetoothLeService.this.b((BluetoothLeService) this.f178a).run();
        }
    }

    public class f implements Runnable {

        /* renamed from: a  reason: collision with root package name */
        public final /* synthetic */ String f179a;

        public f(String str) {
            this.f179a = str;
        }

        public void run() {
            try {
                BluetoothDevice f = BluetoothLeService.this.f((BluetoothLeService) this.f179a);
                BluetoothLeService.this.h = new j(BluetoothLeService.this, null);
                BluetoothLeService.this.h.a(true);
                a.b.a.i.e.b("Ble-connect");
                BluetoothLeService bluetoothLeService = BluetoothLeService.this;
                bluetoothLeService.g = f.connectGatt(bluetoothLeService, false, bluetoothLeService.h, 2);
                BluetoothLeService.this.q = this.f179a;
                BluetoothLeService.this.b((BluetoothLeService) true);
            } catch (IllegalArgumentException e) {
                a.a.a.b.b(BluetoothLeService.F, "Connect failed because of illegal argument.", e);
                BluetoothLeService.this.b((BluetoothLeService) 3, 1);
            }
        }
    }

    public class g extends AdvertisingSetCallback {
        public g() {
        }

        public void onAdvertisingEnabled(AdvertisingSet advertisingSet, boolean z, int i) {
            if (z) {
                a.a.a.b.b(BluetoothLeService.F, "Legacy advertiser should be only disabled on timeout, but was enabled!");
                return;
            }
            AdvertisingSetCallback advertisingSetCallback = BluetoothLeService.this.l;
            if (advertisingSetCallback != null) {
                BluetoothLeService.this.d.stopAdvertisingSet(advertisingSetCallback);
            }
        }

        public void onAdvertisingSetStarted(AdvertisingSet advertisingSet, int i, int i2) {
            a.a.a.b.c(BluetoothLeService.F, "onAdvertisingSetStarted status " + i2 + " advertisingSet: " + advertisingSet + " txPower " + i);
            BluetoothLeService bluetoothLeService = BluetoothLeService.this;
            if (i2 == 0) {
                bluetoothLeService.b((BluetoothLeService) 1);
            } else {
                bluetoothLeService.b((BluetoothLeService) 1, 3);
            }
        }
    }

    public class h extends Handler {
        private static final String b = "BLEService-Delayer";
        private static final int c = 200;
        private static final int d = 1;
        private static final int e = 2;

        public class a implements Runnable {

            /* renamed from: a  reason: collision with root package name */
            public final /* synthetic */ String f182a;
            public final /* synthetic */ CountDownLatch b;

            public a(String str, CountDownLatch countDownLatch) {
                this.f182a = str;
                this.b = countDownLatch;
            }

            public void run() {
                BluetoothLeService.this.a(this.f182a);
                this.b.countDown();
            }
        }

        public class b implements Runnable {

            /* renamed from: a  reason: collision with root package name */
            public final /* synthetic */ CountDownLatch f183a;

            public b(CountDownLatch countDownLatch) {
                this.f183a = countDownLatch;
            }

            public void run() {
                BluetoothLeService.this.g();
                this.f183a.countDown();
            }
        }

        public h(Looper looper) {
            super(looper);
        }

        public synchronized void a() {
            a.a.a.b.a(b, "Post disconnectMsg");
            Message obtainMessage = obtainMessage();
            obtainMessage.what = 2;
            sendMessage(obtainMessage);
        }

        public synchronized void a(String str) {
            a.a.a.b.a(b, "Post connectMsg");
            Message obtainMessage = obtainMessage();
            obtainMessage.what = 1;
            obtainMessage.obj = str;
            sendMessage(obtainMessage);
        }

        public void handleMessage(Message message) {
            CountDownLatch countDownLatch = new CountDownLatch(1);
            int i = message.what;
            if (i == 1) {
                String str = (String) message.obj;
                if (BluetoothLeService.this.j != null) {
                    BluetoothLeService.this.j.post(new a(str, countDownLatch));
                } else {
                    a.a.a.b.e(b, "Receive connect message but handler is null.");
                    BluetoothLeService.this.b((BluetoothLeService) 3, 1);
                }
            } else if (i != 2) {
                a.a.a.b.a(b, "Unable handle msg.what=" + message.what);
                return;
            } else if (BluetoothLeService.this.j != null) {
                BluetoothLeService.this.j.post(new b(countDownLatch));
            }
            try {
                countDownLatch.await();
                Thread.sleep(200);
            } catch (Exception unused) {
            }
        }
    }

    public class i extends IBluetoothLe.b {
        private ArrayMap<String, Integer> s;

        private i() {
            this.s = new ArrayMap<>();
        }

        public /* synthetic */ i(BluetoothLeService bluetoothLeService, a aVar) {
            this();
        }

        @Override // com.share.connect.ble.IBluetoothLe
        public void allowProcessNewConnection() {
            BluetoothLeService.this.f.a();
        }

        @Override // com.share.connect.ble.IBluetoothLe
        public void close() {
            BluetoothLeService.this.f();
        }

        @Override // com.share.connect.ble.IBluetoothLe
        public boolean connect(String str) {
            if (BluetoothLeService.this.n != null) {
                String d = BluetoothLeService.this.n.d(str);
                if (TextUtils.isEmpty(d) || BluetoothLeService.this.i == null) {
                    a.a.a.b.e(BluetoothLeService.F, BluetoothLeService.this.i == null ? "Internal error." : "Can't find mac in scan cache.");
                    return false;
                }
                BluetoothLeService.this.i.a(d);
                return true;
            }
            a.a.a.b.e(BluetoothLeService.F, "Cache is null, do not connect when scan has stopped.");
            return false;
        }

        @Override // com.share.connect.ble.IBluetoothLe
        public void connectDone() {
            a.a.a.b.a(BluetoothLeService.F, "connectDone...");
            if (BluetoothLeService.this.h != null) {
                BluetoothLeService.this.h.a();
            }
            if (BluetoothLeService.this.f != null) {
                BluetoothLeService.this.f.b();
            }
            BluetoothLeService.this.b((BluetoothLeService) false);
        }

        @Override // com.share.connect.ble.IBluetoothLe
        public void disconnect() {
            if (BluetoothLeService.this.i != null) {
                BluetoothLeService.this.i.a();
            }
        }

        @Override // com.share.connect.ble.IBluetoothLe
        public void disconnectWithoutState() {
            a.a.a.b.b(BluetoothLeService.F, "TEST-ONLY METHOD INVOKED!!");
            if (BluetoothLeService.this.g != null) {
                a.a.a.b.a(BluetoothLeService.F, "disconnect gatt client");
                BluetoothLeService.this.g.close();
                BluetoothLeService.this.g = null;
            }
            if (BluetoothLeService.this.e != null && !TextUtils.isEmpty(BluetoothLeService.this.r)) {
                a.a.a.b.a(BluetoothLeService.F, "cancelConnection for " + BluetoothLeService.this.r);
                try {
                    BluetoothLeService.this.e.cancelConnection(BluetoothLeService.this.b.getRemoteDevice(BluetoothLeService.this.r));
                } catch (IllegalArgumentException e) {
                    a.a.a.b.b(BluetoothLeService.F, "cancelConnection failed because of illegal argument.", e);
                }
            }
        }

        @Override // com.share.connect.ble.IBluetoothLe
        public Map getDevicesSignal(int i, int i2) {
            if (BluetoothLeService.this.n == null) {
                a.a.a.b.e(BluetoothLeService.F, "Call signal list while scanning is stopped.");
                return Collections.emptyMap();
            }
            if (i == 0 || this.s.isEmpty()) {
                this.s.clear();
                this.s = BluetoothLeService.this.n.a();
            }
            if (this.s.size() <= i) {
                return Collections.emptyMap();
            }
            ArrayMap arrayMap = new ArrayMap();
            int i3 = 0;
            while (true) {
                if (i3 >= i2) {
                    break;
                }
                int i4 = i3 + i;
                if (i4 >= this.s.size()) {
                    this.s.clear();
                    break;
                }
                arrayMap.put(this.s.keyAt(i4), this.s.valueAt(i4));
                i3++;
            }
            return arrayMap;
        }

        @Override // com.share.connect.ble.IBluetoothLe
        public boolean isDeviceInMatch(String str) {
            if (BluetoothLeService.this.n != null) {
                return BluetoothLeService.this.n.a(str);
            }
            return false;
        }

        @Override // com.share.connect.ble.IBluetoothLe
        public void notifyServerInfo(String str, String str2, String str3, int i, int i2) {
            a.a.a.b.c(BluetoothLeService.F, "Ready to notify server info: m:" + (!str3.equalsIgnoreCase("02:00:00:00:00:00")) + ", f:" + i);
            a.b.a.i.e.b("Ble-notifyCharacteristic");
            BluetoothLeService bluetoothLeService = BluetoothLeService.this;
            byte[] a2 = a.b.a.f.c.a(bluetoothLeService.a(str, str2, str3, i, bluetoothLeService.v, i2).toString());
            if (a2 == null || BluetoothLeService.this.r == null) {
                BluetoothLeService.this.b((BluetoothLeService) 6, 1);
                return;
            }
            BluetoothLeService.this.b((BluetoothLeService) h.b.h.getUuid(), (UUID) a2);
            BluetoothLeService.this.i();
            connectDone();
            BluetoothLeService.this.a((BluetoothLeService) 1, 0);
        }

        @Override // com.share.connect.ble.IBluetoothLe
        public void open(String str, String str2, String str3, String str4, String str5, String str6, boolean z, int i) {
            BluetoothLeService.this.s = str;
            BluetoothLeService.this.t = str2;
            BluetoothLeService bluetoothLeService = BluetoothLeService.this;
            if (str3 == null) {
                str3 = "";
            }
            bluetoothLeService.u = str3;
            BluetoothLeService bluetoothLeService2 = BluetoothLeService.this;
            if (str4 == null) {
                str4 = "";
            }
            bluetoothLeService2.v = str4;
            BluetoothLeService.this.w = str5;
            BluetoothLeService.this.x = str6;
            BluetoothLeService.this.E = z;
            BluetoothLeService.this.y = i;
            BluetoothLeService.this.j();
        }

        @Override // com.share.connect.ble.IBluetoothLe
        public void registerBluetoothLeObserver(BluetoothLeObserver bluetoothLeObserver) {
            BluetoothLeService.this.a(bluetoothLeObserver);
        }

        @Override // com.share.connect.ble.IBluetoothLe
        public void setBandSupported(int i) {
            BluetoothLeService.this.A = i;
        }

        @Override // com.share.connect.ble.IBluetoothLe
        public void setP2pDeviceMac(String str) {
            if (!TextUtils.isEmpty(BluetoothLeService.this.B) && !TextUtils.equals(BluetoothLeService.this.B, str)) {
                a.a.a.b.b(BluetoothLeService.F, "Warning!!!! Mac address changed from " + BluetoothLeService.this.B + " to " + str);
            }
            BluetoothLeService.this.B = str;
        }

        @Override // com.share.connect.ble.IBluetoothLe
        public void startScan() {
            BluetoothLeService.this.p();
        }

        @Override // com.share.connect.ble.IBluetoothLe
        public void stopAdvertise() throws RemoteException {
            BluetoothLeService.this.q();
        }

        @Override // com.share.connect.ble.IBluetoothLe
        public void stopScan() {
            BluetoothLeService.this.r();
        }

        @Override // com.share.connect.ble.IBluetoothLe
        public void unregisterBluetoothLeObserver(BluetoothLeObserver bluetoothLeObserver) {
            BluetoothLeService.this.b(bluetoothLeObserver);
        }
    }

    public class j extends BluetoothGattCallback {
        private static final String f = "GattClientCallback";

        /* renamed from: a  reason: collision with root package name */
        private int f184a;
        private boolean b;
        private boolean c;
        private AtomicBoolean d;

        public class a implements Runnable {
            public a() {
            }

            public void run() {
                try {
                    BluetoothDevice remoteDevice = BluetoothLeService.this.b.getRemoteDevice(BluetoothLeService.this.q);
                    BluetoothLeService bluetoothLeService = BluetoothLeService.this;
                    bluetoothLeService.g = remoteDevice.connectGatt(bluetoothLeService, false, bluetoothLeService.h);
                } catch (IllegalArgumentException e) {
                    a.a.a.b.b(j.f, "Reconnect failed because of illegal argument.", e);
                    BluetoothLeService.this.b((BluetoothLeService) 3, 1);
                }
            }
        }

        private j() {
            this.f184a = 2;
            this.b = false;
            this.c = false;
            this.d = new AtomicBoolean(false);
        }

        public /* synthetic */ j(BluetoothLeService bluetoothLeService, a aVar) {
            this();
        }

        private void a(BluetoothGatt bluetoothGatt) {
            if (bluetoothGatt.discoverServices()) {
                a.a.a.b.a(f, "Discover service action success.");
                return;
            }
            a.a.a.b.b(f, "Discover service action failed.");
            BluetoothLeService.this.b((BluetoothLeService) 3, 1);
        }

        public void a() {
            a.a.a.b.a(f, "Connect done.");
            this.b = true;
            if (this.c && BluetoothLeService.this.g != null) {
                BluetoothLeService.this.g.close();
            }
        }

        public void a(boolean z) {
            a.a.a.b.c(f, "Set positive: " + z);
            this.c = z;
        }

        public void onCharacteristicChanged(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
            a.a.a.b.a(f, "onCharacteristicChanged: connectDone=" + this.b + ", device=" + bluetoothGatt.getDevice() + ", targetDevice=" + BluetoothLeService.this.q + ", characteristic=" + a.b.a.f.h.a(bluetoothGattCharacteristic.getUuid().toString()) + ", value=" + a.b.a.f.c.a(bluetoothGattCharacteristic.getValue()));
            boolean equals = TextUtils.equals(BluetoothLeService.this.q, Objects.toString(bluetoothGatt.getDevice()));
            if (!this.b && equals && h.b.h.getUuid().equals(bluetoothGattCharacteristic.getUuid())) {
                BluetoothLeService.this.d((BluetoothLeService) a.b.a.f.c.b(a.b.a.f.c.c(bluetoothGattCharacteristic.getValue())));
            }
        }

        public void onConnectionStateChange(BluetoothGatt bluetoothGatt, int i, int i2) {
            int i3;
            a.a.a.b.c(f, "onConnectionStateChange: isConnectDone=" + this.b + ", device=" + bluetoothGatt.getDevice() + ", targetDevice=" + BluetoothLeService.this.q + ", status=" + i + ", newState=" + i2);
            boolean equals = TextUtils.equals(BluetoothLeService.this.q, Objects.toString(bluetoothGatt.getDevice()));
            if (i != 0) {
                a.a.a.b.e(f, "Gatt client status: " + i);
                if (this.b || !equals) {
                    bluetoothGatt.close();
                } else {
                    if (i == 133 && (i3 = this.f184a) > 0) {
                        this.f184a = i3 - 1;
                        a.a.a.b.e(f, "Gatt reconnect...");
                        bluetoothGatt.close();
                        if (BluetoothLeService.this.j != null) {
                            BluetoothLeService.this.j.postDelayed(new a(), 300);
                        } else {
                            a.a.a.b.e(f, "Handler is null, cancel reconnect.");
                        }
                    }
                    BluetoothLeService.this.b((BluetoothLeService) 3, 1);
                }
                if (i == 257) {
                    a.a.a.b.b(f, "Receives GATT_FAILURE !!");
                }
            } else if (i2 == 0) {
                a.a.a.b.e(f, "Gatt disconnected");
                if (this.b || !equals) {
                    bluetoothGatt.close();
                } else {
                    BluetoothLeService.this.g();
                }
            } else if (i2 == 2 && !this.b && equals) {
                BluetoothLeService.this.p.set(true);
                if (this.d.compareAndSet(false, true)) {
                    a.b.a.i.e.a("Ble-connect");
                    a.b.a.i.e.b("Ble-discoverServices");
                    if (!bluetoothGatt.requestMtu(512)) {
                        a(bluetoothGatt);
                        return;
                    }
                    return;
                }
                a.a.a.b.e(f, "Twice in onConnectionStateChange, ignored.");
            }
        }

        public void onMtuChanged(BluetoothGatt bluetoothGatt, int i, int i2) {
            a.a.a.b.a(f, "onMtuChanged: mtu=" + i + ", status=" + i2);
            a.a.a.b.a(f, "Connected, Trying discoverService...");
            a(bluetoothGatt);
        }

        public void onServicesDiscovered(BluetoothGatt bluetoothGatt, int i) {
            a.a.a.b.a(f, "onServicesDiscovered: connectDone=" + this.b + ", device=" + bluetoothGatt.getDevice() + ", targetDevice=" + BluetoothLeService.this.q + ", status=" + i);
            boolean equals = TextUtils.equals(BluetoothLeService.this.q, Objects.toString(bluetoothGatt.getDevice()));
            if (i != 0) {
                a.a.a.b.e(f, "ServicesDiscover failed with status: " + i);
                if (this.b || !equals) {
                    bluetoothGatt.close();
                } else {
                    BluetoothLeService.this.b((BluetoothLeService) 3, 1);
                }
            } else if (!this.b && equals) {
                a.a.a.b.a(f, "Connected and services discovered ! Hooyaaah!");
                a.b.a.i.e.a("Ble-discoverServices");
                a.b.a.i.e.b("Ble-writeCharacteristics");
                if (bluetoothGatt.getService(h.b.f.getUuid()) != null) {
                    String substring = UUID.randomUUID().toString().substring(0, 6);
                    if (BluetoothLeService.this.a((BluetoothLeService) h.b.g.getUuid(), (UUID) a.b.a.f.c.a(BluetoothLeService.this.e((BluetoothLeService) substring).toString()))) {
                        BluetoothLeService.this.a((BluetoothLeService) h.b.h.getUuid());
                        BluetoothLeService.this.b((BluetoothLeService) false);
                        synchronized (BluetoothLeService.this.D) {
                            for (BluetoothLeObserver bluetoothLeObserver : BluetoothLeService.this.D) {
                                try {
                                    bluetoothLeObserver.onPinAvailable(substring);
                                } catch (RemoteException e2) {
                                    a.a.a.b.b(f, "Error when invoke onPinAvailable.", e2);
                                }
                            }
                        }
                        return;
                    }
                    BluetoothLeService.this.b((BluetoothLeService) 6, 1);
                }
            }
        }
    }

    public class k extends BluetoothGattServerCallback {
        private static final String j = "GattServerCallback";

        /* renamed from: a  reason: collision with root package name */
        private boolean f186a;
        private boolean b;
        private Map<String, byte[]> c;
        private Map<String, UUID> d;
        private List<Pair<BluetoothDevice, String>> e;
        private boolean f;
        private String g;
        private l h;

        private k() {
            this.f186a = true;
            this.b = true;
            this.c = new ArrayMap();
            this.d = new ArrayMap();
            this.e = new LinkedList();
            this.f = true;
        }

        public /* synthetic */ k(BluetoothLeService bluetoothLeService, a aVar) {
            this();
        }

        private void a(BluetoothDevice bluetoothDevice, byte[] bArr) {
            if (this.f || bluetoothDevice.getAddress().equals(BluetoothLeService.this.r)) {
                c();
                BluetoothLeService.this.r = bluetoothDevice.getAddress();
                BluetoothLeService.this.c((BluetoothLeService) a.b.a.f.c.b(bArr));
                return;
            }
            a.a.a.b.c(j, "There is already a phone connecting, caching client info. phone address:" + bluetoothDevice.getAddress());
            this.e.add(new Pair<>(bluetoothDevice, a.b.a.f.c.b(bArr)));
        }

        private byte[] a(BluetoothDevice bluetoothDevice, BluetoothGattCharacteristic bluetoothGattCharacteristic, boolean z, int i2, byte[] bArr) {
            if (!z) {
                return bArr;
            }
            this.d.put(bluetoothDevice.getAddress(), bluetoothGattCharacteristic.getUuid());
            byte[] bArr2 = this.c.get(bluetoothDevice.getAddress());
            if (bArr2 == null) {
                bArr2 = new byte[1024];
                this.c.put(bluetoothDevice.getAddress(), bArr2);
            }
            if (i2 < 0 || bArr.length + i2 > bArr2.length) {
                return null;
            }
            System.arraycopy(bArr, 0, bArr2, i2, bArr.length);
            return null;
        }

        private void c() {
            this.f186a = false;
            this.f = false;
        }

        public void a() {
            if (!this.e.isEmpty()) {
                Pair<BluetoothDevice, String> pair = this.e.get(0);
                BluetoothDevice bluetoothDevice = (BluetoothDevice) pair.first;
                BluetoothLeService.this.r = bluetoothDevice.getAddress();
                a.a.a.b.c(j, "process cached client info. phone address:" + bluetoothDevice.getAddress());
                c();
                BluetoothLeService.this.c((BluetoothLeService) ((String) pair.second));
                this.e.remove(0);
                return;
            }
            this.f = true;
        }

        public void a(String str, l lVar) {
            this.g = str;
            this.h = lVar;
        }

        public void a(boolean z) {
            a.a.a.b.c(j, "Set positive: " + z);
            this.b = z;
        }

        public void b() {
            try {
                this.f186a = true;
                if (this.b) {
                    BluetoothDevice remoteDevice = BluetoothLeService.this.b.getRemoteDevice(BluetoothLeService.this.r);
                    a.a.a.b.c(j, "connectDone for " + BluetoothLeService.this.r);
                    BluetoothLeService.this.e.cancelConnection(remoteDevice);
                }
            } catch (IllegalArgumentException e2) {
                a.a.a.b.e(j, "cancelConnection for " + BluetoothLeService.this.r + " failed: " + e2.getMessage());
            }
        }

        public void d() {
            this.e.clear();
            this.f = true;
        }

        public void onCharacteristicWriteRequest(BluetoothDevice bluetoothDevice, int i2, BluetoothGattCharacteristic bluetoothGattCharacteristic, boolean z, boolean z2, int i3, byte[] bArr) {
            byte[] a2;
            a.a.a.b.a(j, "onCharacteristicWriteRequest: device=" + bluetoothDevice + ", requestId=" + i2 + ", offset=" + i3 + ", preparedWrite=" + z + ", responseNeeded=" + z2 + ", characteristic={" + bluetoothGattCharacteristic.getUuid() + ", " + a.b.a.f.c.a(bArr) + "}");
            if (BluetoothLeService.this.e != null && z2) {
                BluetoothLeService.this.e.sendResponse(bluetoothDevice, i2, 0, i3, bArr);
            }
            if (h.b.g.getUuid().equals(bluetoothGattCharacteristic.getUuid()) && (a2 = a(bluetoothDevice, bluetoothGattCharacteristic, z, i3, bArr)) != null) {
                a(bluetoothDevice, a2);
            }
        }

        public void onConnectionStateChange(BluetoothDevice bluetoothDevice, int i2, int i3) {
            if (bluetoothDevice == null) {
                a.a.a.b.b(j, "bluetooth device cannot be null.");
                return;
            }
            a.a.a.b.c(j, "onConnectionStateChange: device=" + bluetoothDevice + ", targetMac=" + BluetoothLeService.this.r + ", status=" + i2 + ", newState=" + i3);
            if (TextUtils.equals(bluetoothDevice.getAddress(), BluetoothLeService.this.q) && i3 == 0) {
                a.a.a.b.c(j, "Client(self) disconnected with GATT server.");
                BluetoothLeService.this.p.set(false);
            }
            if (TextUtils.equals(bluetoothDevice.getAddress(), this.g)) {
                a.a.a.b.b(j, "Listen device disconnected.");
                l lVar = this.h;
                if (lVar != null) {
                    lVar.a();
                }
                this.g = null;
                this.h = null;
            }
            boolean equals = TextUtils.equals(BluetoothLeService.this.r, bluetoothDevice.getAddress());
            if (!this.f186a && equals) {
                if (i2 != 0 || i3 == 0) {
                    b();
                    d();
                    BluetoothLeService.this.b((BluetoothLeService) 4, 1);
                }
            }
        }

        public void onExecuteWrite(BluetoothDevice bluetoothDevice, int i2, boolean z) {
            String str;
            a.a.a.b.a(j, "onExecuteWrite: device=" + bluetoothDevice + ", requestId=" + i2 + ", execute=" + z);
            byte[] remove = this.c.remove(bluetoothDevice.getAddress());
            UUID remove2 = this.d.remove(bluetoothDevice.getAddress());
            if (remove2 == null) {
                str = "Characteristic Uuid is null.";
            } else if (remove == null) {
                str = "Cache byte[] is null.";
            } else {
                a.a.a.b.a(j, "Cache byte: " + a.b.a.f.c.a(remove));
                if (BluetoothLeService.this.e != null) {
                    BluetoothLeService.this.e.sendResponse(bluetoothDevice, i2, 0, 0, null);
                }
                if (h.b.g.getUuid().equals(remove2)) {
                    a(bluetoothDevice, remove);
                    return;
                }
                return;
            }
            a.a.a.b.e(j, str);
        }

        public void onMtuChanged(BluetoothDevice bluetoothDevice, int i2) {
            a.a.a.b.a(j, "onMtuChanged: device=" + bluetoothDevice.getAddress() + ", mtu=" + i2);
        }

        public void onServiceAdded(int i2, BluetoothGattService bluetoothGattService) {
            a.a.a.b.c(j, "onServiceAdded: " + a.b.a.f.h.b(bluetoothGattService.getUuid().toString()));
        }
    }

    public interface l {
        void a();
    }

    private AdvertiseSettings a(boolean z2) {
        AdvertiseSettings.Builder builder = new AdvertiseSettings.Builder();
        builder.setAdvertiseMode(2);
        builder.setTxPowerLevel(3);
        builder.setTimeout(0);
        return builder.build();
    }

    private String a(String str, int i2) {
        while (a.b.a.f.c.a(str).length > i2) {
            str = str.substring(0, str.length() - 1);
        }
        a.a.a.b.a(F, "Trim string: " + str);
        return str;
    }

    private List<ScanFilter> a() {
        ArrayList arrayList = new ArrayList();
        ScanFilter.Builder builder = new ScanFilter.Builder();
        builder.setServiceUuid(h.b.b);
        arrayList.add(builder.build());
        return arrayList;
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private JSONObject a(String str, String str2, String str3, int i2, String str4, int i3) {
        try {
            JSONObject jSONObject = new JSONObject();
            jSONObject.put(h.a.b, str4);
            jSONObject.put(h.a.g, str);
            jSONObject.put(h.a.h, str2);
            jSONObject.put(h.a.e, str3);
            jSONObject.put(h.a.i, i2);
            jSONObject.put(h.a.j, 0);
            jSONObject.put(h.a.k, i3);
            return jSONObject;
        } catch (Exception e2) {
            a.a.a.b.b(F, "Generate server info failed.", e2);
            return null;
        }
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void a(int i2) {
        BluetoothAdapter bluetoothAdapter = this.b;
        if (bluetoothAdapter != null) {
            if (!bluetoothAdapter.isEnabled()) {
                IntentFilter intentFilter = new IntentFilter("android.bluetooth.adapter.action.STATE_CHANGED");
                b bVar = new b(i2);
                this.o = bVar;
                registerReceiver(bVar, intentFilter);
                boolean enable = this.b.enable();
                a.a.a.b.c(F, "Enabling Bluetooth Action: " + enable);
                if (!enable) {
                    try {
                        unregisterReceiver(this.o);
                    } catch (RuntimeException unused) {
                    }
                } else {
                    return;
                }
            } else if (l()) {
                return;
            } else {
                if (i2 > 0) {
                    a(i2 - 1);
                    return;
                }
            }
            b(1, 2);
        }
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void a(boolean z2, DeviceCache.BtDevice btDevice) {
        synchronized (this.D) {
            for (BluetoothLeObserver bluetoothLeObserver : this.D) {
                if (z2) {
                    try {
                        bluetoothLeObserver.onDeviceMatch(btDevice);
                    } catch (RemoteException e2) {
                        a.a.a.b.b(F, "Observer." + (z2 ? "onDeviceMatch" : "onDeviceLost") + " failed", e2);
                    }
                } else {
                    bluetoothLeObserver.onDeviceLost(btDevice);
                }
            }
        }
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private boolean a(int i2, int i3) {
        StringBuilder sb;
        a.a.a.b.c(F, "Change state to " + i3 + " if current state is " + i2);
        boolean compareAndSet = this.z.compareAndSet(i2, i3);
        if (compareAndSet) {
            a.a.a.b.c(F, sb.append("Change state to ").append(i3).append(" success").toString());
        } else {
            sb = new StringBuilder();
            a.a.a.b.e(F, sb.append("Change state to ").append(i3).append(" failed").toString());
        }
        return compareAndSet;
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private boolean a(UUID uuid) {
        String str;
        BluetoothGatt bluetoothGatt = this.g;
        if (bluetoothGatt != null) {
            List<BluetoothGattService> services = bluetoothGatt.getServices();
            if (services != null && services.size() > 0) {
                for (BluetoothGattService bluetoothGattService : services) {
                    BluetoothGattCharacteristic characteristic = bluetoothGattService.getCharacteristic(uuid);
                    if (characteristic != null) {
                        return this.g.setCharacteristicNotification(characteristic, true);
                    }
                }
            }
            str = "writeCharacteristic: Characteristic(" + a.b.a.f.h.a(uuid.toString()) + ") not found.";
        } else {
            str = "subscribeCharacteristic: mBluetoothGatt is null, already disconnected ?";
        }
        a.a.a.b.e(F, str);
        return false;
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private boolean a(UUID uuid, byte[] bArr) {
        String str;
        a.a.a.b.a(F, "Trying to send write characteristic(" + a.b.a.f.h.a(uuid.toString()) + ") request to remote gatt server, value=" + a.b.a.f.c.a(bArr));
        BluetoothGatt bluetoothGatt = this.g;
        if (bluetoothGatt != null) {
            List<BluetoothGattService> services = bluetoothGatt.getServices();
            if (services != null && services.size() > 0) {
                for (BluetoothGattService bluetoothGattService : services) {
                    BluetoothGattCharacteristic characteristic = bluetoothGattService.getCharacteristic(uuid);
                    if (characteristic != null) {
                        characteristic.setValue(bArr);
                        return this.g.writeCharacteristic(characteristic);
                    }
                }
            }
            str = "writeCharacteristic: Characteristic(" + a.b.a.f.h.a(uuid.toString()) + ") not found.";
        } else {
            str = "writeCharacteristic: mBluetoothGatt is null, already disconnected ?";
        }
        a.a.a.b.e(F, str);
        return false;
    }

    private ScanSettings b() {
        ScanSettings.Builder builder = new ScanSettings.Builder();
        builder.setScanMode(2);
        return builder.build();
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private Runnable b(String str) {
        return new f(str);
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void b(int i2) {
        synchronized (this.D) {
            for (BluetoothLeObserver bluetoothLeObserver : this.D) {
                try {
                    bluetoothLeObserver.onSuccess(i2);
                } catch (RemoteException e2) {
                    a.a.a.b.b(F, "Observer.onSuccess(" + i2 + ") failed.", e2);
                }
            }
        }
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void b(int i2, int i3) {
        synchronized (this.D) {
            for (BluetoothLeObserver bluetoothLeObserver : this.D) {
                try {
                    bluetoothLeObserver.onFailure(i2, i3);
                } catch (RemoteException e2) {
                    a.a.a.b.b(F, "Observer.onFailure(" + i2 + ", " + i3 + ") failed.", e2);
                }
            }
        }
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void b(UUID uuid, byte[] bArr) {
        String str;
        BluetoothGattCharacteristic characteristic = this.e.getService(h.b.f.getUuid()).getCharacteristic(uuid);
        if (characteristic == null) {
            str = "notify server info failed. characteristic is null ";
        } else if (!characteristic.setValue(bArr)) {
            str = "notify server info failed. setting characteristic not successful";
        } else {
            this.e.notifyCharacteristicChanged(this.b.getRemoteDevice(this.r), characteristic, true);
            return;
        }
        a.a.a.b.b(F, str);
        b(3, 1);
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void b(boolean z2) {
        a.a.a.b.c(F, "setConnectTimeout: " + z2);
        if (z2) {
            Handler handler = this.j;
            if (handler != null) {
                handler.postDelayed(this.k, 30000);
                return;
            }
            a.a.a.b.e(F, "Enable timeout but handler is null, closed?");
            b(3, 1);
            return;
        }
        Handler handler2 = this.j;
        if (handler2 != null) {
            handler2.removeCallbacks(this.k);
        }
    }

    private AdvertiseData c() {
        return a.b.a.f.a.a(this.w, this.s, this.t, this.x, this.y, this.E, getApplicationContext());
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void c(String str) {
        List<BluetoothLeObserver> list;
        a.a.a.b.c(F, "Client info: " + str);
        try {
            JSONObject jSONObject = new JSONObject(str);
            String string = jSONObject.getString(h.a.f21a);
            String string2 = jSONObject.getString(h.a.b);
            String string3 = jSONObject.getString(h.a.f);
            int i2 = jSONObject.getInt(h.a.c);
            String string4 = jSONObject.getString(h.a.e);
            int optInt = jSONObject.optInt(h.a.k, 1001);
            String optString = jSONObject.optString(h.a.l, null);
            int optInt2 = jSONObject.optInt(h.a.n, 0);
            List<BluetoothLeObserver> list2 = this.D;
            synchronized (list2) {
                try {
                    for (BluetoothLeObserver bluetoothLeObserver : this.D) {
                        list = list2;
                        try {
                            bluetoothLeObserver.onClientInfoReceived(string, string2, string3, i2, string4, optInt, optString, optInt2);
                        } catch (RemoteException e2) {
                            a.a.a.b.b(F, "Observer.onClientInfoReceived(...) failed.", e2);
                            b(4, 1);
                        } catch (Throwable th) {
                            th = th;
                            throw th;
                        }
                        list2 = list;
                    }
                } catch (Throwable th2) {
                    th = th2;
                    list = list2;
                    throw th;
                }
            }
        } catch (Exception e3) {
            a.a.a.b.b(F, "Parsing client info failed.", e3);
            b(4, 1);
        }
    }

    private AdvertiseData d() {
        return a.b.a.f.a.a(this.v);
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void d(String str) {
        try {
            JSONObject jSONObject = new JSONObject(str);
            String string = jSONObject.getString(h.a.g);
            String string2 = jSONObject.getString(h.a.h);
            String string3 = jSONObject.getString(h.a.e);
            int i2 = jSONObject.getInt(h.a.i);
            synchronized (this.D) {
                for (BluetoothLeObserver bluetoothLeObserver : this.D) {
                    try {
                        bluetoothLeObserver.onServerInfoReceived(string, string2, string3, i2);
                    } catch (RemoteException e2) {
                        a.a.a.b.b(F, "Observer.onServerInfoReceived(...) failed.", e2);
                        b(3, 1);
                    }
                }
            }
        } catch (Exception e3) {
            a.a.a.b.b(F, "Parsing server info failed.", e3);
            b(3, 1);
        }
    }

    private BluetoothGattService e() {
        BluetoothGattService bluetoothGattService = new BluetoothGattService(h.b.f.getUuid(), 0);
        BluetoothGattCharacteristic bluetoothGattCharacteristic = new BluetoothGattCharacteristic(h.b.g.getUuid(), 8, 16);
        BluetoothGattCharacteristic bluetoothGattCharacteristic2 = new BluetoothGattCharacteristic(h.b.h.getUuid(), 16, 1);
        bluetoothGattCharacteristic2.addDescriptor(new BluetoothGattDescriptor(h.b.f22a.getUuid(), 16));
        bluetoothGattService.addCharacteristic(bluetoothGattCharacteristic);
        bluetoothGattService.addCharacteristic(bluetoothGattCharacteristic2);
        return bluetoothGattService;
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private JSONObject e(String str) {
        try {
            JSONObject jSONObject = new JSONObject();
            jSONObject.put(h.a.f21a, this.s);
            jSONObject.put(h.a.b, this.u);
            jSONObject.put(h.a.d, str);
            jSONObject.put(h.a.c, this.A);
            jSONObject.put(h.a.e, this.B);
            a.a.a.b.a(F, "Client info: " + jSONObject.toString());
            return jSONObject;
        } catch (Exception e2) {
            a.a.a.b.b(F, "Generate receiver info failed.", e2);
            return null;
        }
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private BluetoothDevice f(String str) {
        BluetoothDevice remoteDevice = this.b.getRemoteDevice(str);
        a.a.a.b.c(F, "Bond state = " + remoteDevice.getBondState());
        return remoteDevice;
    }

    private boolean h() {
        this.d = this.b.getBluetoothLeAdvertiser();
        this.c = a.b.a.f.g.a(this.b.getBluetoothLeScanner());
        a.a.a.b.c(F, "initialize: advertiser=" + (this.d != null) + ", scanner=" + (this.c != null));
        return (this.d == null || this.c == null) ? false : true;
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void i() {
        synchronized (this.D) {
            for (BluetoothLeObserver bluetoothLeObserver : this.D) {
                try {
                    bluetoothLeObserver.onServerAddressSent();
                } catch (Exception e2) {
                    a.a.a.b.b(F, "notifyServerAddressSent Exception", e2);
                }
            }
        }
    }

    private void k() {
        a.a.a.b.c(F, "Reset state.");
        this.z.set(0);
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private boolean l() {
        try {
            if (!h()) {
                return false;
            }
            n();
            return true;
        } catch (IllegalStateException e2) {
            a.a.a.b.e(F, "Setup Bt failed because of illegal state.", e2);
            return false;
        }
    }

    private void m() throws IllegalStateException {
        int i2;
        a.a.a.b.c(F, "Starting advertiser.");
        int i3 = 1;
        AdvertisingSetParameters.Builder txPowerLevel = new AdvertisingSetParameters.Builder().setConnectable(true).setScannable(true).setLegacyMode(true).setPrimaryPhy(1).setTxPowerLevel(1);
        try {
            Field declaredField = AdvertisingSetParameters.Builder.class.getDeclaredField("mInterval");
            declaredField.setAccessible(true);
            declaredField.set(txPowerLevel, 48);
        } catch (Exception e2) {
            a.a.a.b.b(F, "set Advertising interval failed. ", e2);
        }
        AdvertisingSetParameters build = txPowerLevel.build();
        AdvertiseSettings a2 = a(true);
        AdvertiseData c2 = c();
        AdvertiseData d2 = d();
        int timeout = a2.getTimeout();
        if (timeout > 0) {
            if (timeout >= 10) {
                i3 = timeout / 10;
            }
            i2 = i3;
        } else {
            i2 = 0;
        }
        BluetoothLeAdvertiser bluetoothLeAdvertiser = this.d;
        if (bluetoothLeAdvertiser != null) {
            g gVar = new g();
            this.l = gVar;
            bluetoothLeAdvertiser.startAdvertisingSet(build, c2, d2, null, null, i2, 0, gVar);
        }
    }

    private boolean o() {
        a.a.a.b.c(F, "Starting Gatt Server");
        if (this.e != null) {
            a.a.a.b.e(F, "startGattServer while mBluetoothGattServer is not null");
            this.e.close();
            this.e = null;
        }
        this.f.d();
        this.f.a(false);
        BluetoothGattServer openGattServer = this.f174a.openGattServer(this, this.f);
        this.e = openGattServer;
        if (openGattServer != null) {
            openGattServer.addService(e());
        } else {
            a.a.a.b.b(F, "Opening gatt server failed.");
            b(1, 3);
        }
        return this.e != null;
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void q() {
        BluetoothLeAdvertiser bluetoothLeAdvertiser;
        AdvertisingSetCallback advertisingSetCallback;
        a.a.a.b.c(F, "Stopping advertisers.");
        if (!(!this.b.isEnabled() || (bluetoothLeAdvertiser = this.d) == null || (advertisingSetCallback = this.l) == null)) {
            bluetoothLeAdvertiser.stopAdvertisingSet(advertisingSetCallback);
        }
        this.f.d();
        this.l = null;
    }

    public void a(BluetoothLeObserver bluetoothLeObserver) {
        synchronized (this.D) {
            if (!this.D.contains(bluetoothLeObserver)) {
                this.D.add(bluetoothLeObserver);
            }
        }
    }

    public synchronized void a(String str) {
        a.a.a.b.c(F, "Connecting device=" + str);
        if (this.b == null) {
            a.a.a.b.b(F, "BluetoothAdapter not initialized.");
            b(3, 2);
        } else if (str == null) {
            a.a.a.b.b(F, "Invalid address.");
            b(3, 4);
        } else if (!a(0, 1)) {
            a.a.a.b.e(F, "Conflicted. state is busy now.");
            b(3, 6);
        } else {
            if (this.g != null) {
                a.a.a.b.e(F, "Disconnecting existing different bluetoothGatt connection.");
                this.h.a();
                this.f.a(this.q, new e(str));
                this.g.close();
                this.g = null;
                Handler handler = this.j;
                if (handler != null) {
                    handler.postDelayed(b(str), 500);
                } else {
                    a.a.a.b.e(F, "Handler is null, share service may already closed.");
                    b(3, 1);
                }
            } else {
                b(str).run();
            }
        }
    }

    public void b(BluetoothLeObserver bluetoothLeObserver) {
        synchronized (this.D) {
            this.D.remove(bluetoothLeObserver);
        }
    }

    public void f() {
        a.a.a.b.c(F, "Closing...");
        Handler handler = this.j;
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            this.j = null;
        }
        h hVar = this.i;
        if (hVar != null) {
            hVar.removeCallbacksAndMessages(null);
            Looper looper = hVar.getLooper();
            if (looper != null) {
                looper.quitSafely();
            }
            this.i = null;
        }
        try {
            unregisterReceiver(this.o);
        } catch (Exception unused) {
        }
        if (this.b.isEnabled()) {
            BluetoothGatt bluetoothGatt = this.g;
            if (bluetoothGatt != null) {
                bluetoothGatt.close();
            }
            BluetoothGattServer bluetoothGattServer = this.e;
            if (bluetoothGattServer != null) {
                bluetoothGattServer.close();
            }
            a.b.a.f.g gVar = this.c;
            if (!(gVar == null || this.m == null)) {
                gVar.a();
            }
        }
        k();
        q();
        g();
        this.d = null;
        this.g = null;
        this.e = null;
        this.c = null;
        this.m = null;
        a.a.a.b.c(F, "Closed.");
    }

    public synchronized void g() {
        a.a.a.b.c(F, "disconnect...");
        k();
        if (this.g != null) {
            a.a.a.b.c(F, "close exist bluetoothGatt connection");
            this.g.close();
            this.g = null;
        }
        if (this.e != null && !TextUtils.isEmpty(this.r)) {
            try {
                BluetoothDevice remoteDevice = this.b.getRemoteDevice(this.r);
                a.a.a.b.c(F, "cancelConnection for " + this.r);
                this.e.cancelConnection(remoteDevice);
            } catch (IllegalArgumentException e2) {
                a.a.a.b.b(F, "cancelConnection failed because of illegal argument.", e2);
            }
        }
        b(false);
        this.r = null;
        this.q = null;
        this.p.set(false);
    }

    public void j() {
        a.a.a.b.c(F, "Opening...");
        this.j = new Handler(Looper.getMainLooper());
        HandlerThread handlerThread = new HandlerThread("ConnectDelayer");
        handlerThread.start();
        if (handlerThread.getLooper() != null) {
            this.i = new h(handlerThread.getLooper());
        }
        a(1);
    }

    public void n() {
        if (o()) {
            try {
                m();
            } catch (Exception e2) {
                a.a.a.b.c(F, "startAdvertising() e:" + e2);
            }
        }
    }

    public IBinder onBind(Intent intent) {
        return this.C;
    }

    public void onCreate() {
        super.onCreate();
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService("bluetooth");
        this.f174a = bluetoothManager;
        if (bluetoothManager != null) {
            this.b = bluetoothManager.getAdapter();
        }
        if (this.f174a == null || this.b == null) {
            a.a.a.b.b(F, "mBluetoothManager=" + this.f174a + ", mBluetoothAdapter=" + this.b);
        }
    }

    public void onDestroy() {
        super.onDestroy();
        f();
    }

    public void p() {
        a.a.a.b.c(F, "Starting scan...");
        DeviceCache deviceCache = new DeviceCache();
        this.n = deviceCache;
        deviceCache.a(new c());
        a.b.a.f.g gVar = this.c;
        List<ScanFilter> a2 = a();
        ScanSettings b2 = b();
        d dVar = new d();
        this.m = dVar;
        gVar.a(a2, b2, dVar);
    }

    public void r() {
        a.a.a.b.c(F, "Stopping scan...");
        this.n = null;
        if (!this.b.isEnabled()) {
            a.a.a.b.e(F, "Stop scan after bluetooth down, do nothing.");
            return;
        }
        a.b.a.f.g gVar = this.c;
        if (gVar != null && this.m != null) {
            gVar.a();
            this.m = null;
            a.a.a.b.c(F, "Stop scan success");
        }
    }
}
