package a.c.a.b;

import a.a.a.b;
import a.c.b.z.g.e;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.IBinder;
import com.ucar.connect.aoa.UsbNative;
import com.ucar.vehiclesdk.UCarConnectState;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.regex.Pattern;

public class c {
    private static final int A;
    private static final int B;
    private static final int C;
    private static final int D;
    private static final int E;
    private static final int F;
    private static final int G;
    private static final int H;
    private static final int I;
    private static final int J;
    private static final int K;
    private static final int L;
    private static final String M;
    private static final String N;
    private static final String O;
    private static final String P;
    private static final String Q;
    private static final int R;
    private static final int S;
    private static final int T;
    private static final int U;
    private static final int V;
    private static final int W;
    private static final int X;
    private static final int Y;
    private static final int Z;
    private static final int a0;
    private static final int b0;
    private static final int c0;
    private static final int d0;
    private static final int e0;
    private static final int f0;
    private static final int g0;
    private static final int h0;
    private static final int i0;
    private static final int j0;
    private static final int k0;
    private static final c l0 = new c();
    private static final int m0;
    private static final Map<Integer, String> n0;
    private static final String o;
    private static final String p;
    private static final String q;
    private static final String r;
    private static final String s;
    private static final String t;
    private static final int u;
    private static final int v;
    private static final int w;
    private static final int x;
    private static final int y;
    private static final int z;

    /* renamed from: a */
    private Context f59a = null;
    private UsbManager b = null;
    private UsbDevice c = null;
    private UsbInterface d = null;
    private UsbDeviceConnection e = null;
    private UsbEndpoint f = null;
    private UsbEndpoint g = null;
    private int h = 0;
    private int i = 0;
    private int j = 0;
    private String k;
    private CountDownLatch l;
    private boolean m = false;
    private boolean n = false;

    static {
        HashMap hashMap = new HashMap();
        n0 = hashMap;
        hashMap.put(Integer.valueOf((int) G), "google");
        hashMap.put(8921, "oppo");
        hashMap.put(11669, "vivo");
        hashMap.put(Integer.valueOf((int) UCarConnectState.ErrorCode.ERROR_USER_INTERVENTION_TIMEOUT), "xiaomi");
        hashMap.put(10864, "oneplus");
    }

    private c() {
    }

    private int a(int i2, int i3, byte[] bArr) {
        UsbDeviceConnection usbDeviceConnection = this.e;
        if (usbDeviceConnection == null) {
            return -1;
        }
        return usbDeviceConnection.controlTransfer(64, i2, 0, i3, bArr, bArr == null ? 0 : bArr.length, 0);
    }

    private int a(byte[] bArr) {
        UsbDeviceConnection usbDeviceConnection = this.e;
        if (usbDeviceConnection == null) {
            return -1;
        }
        return usbDeviceConnection.controlTransfer(e.y, 51, 0, 0, bArr, bArr == null ? 0 : bArr.length, 0);
    }

    private int a(byte[] bArr, int i2, int i3) {
        int a2 = UsbNative.a(this.e, this.f, bArr, i2, i3, 0);
        if (a2 < 0) {
            b.b(o, "bulkTransferIn error, ret = " + a2 + " , expect len = " + i3 + " , offset = " + i2);
            try {
                CountDownLatch countDownLatch = this.l;
                if (countDownLatch != null) {
                    if (!countDownLatch.await(300, TimeUnit.MILLISECONDS)) {
                        throw new IOException("wait reconnect usb device timeout.");
                    }
                }
                a2 = UsbNative.a(this.e, this.f, bArr, i2, i3, 0);
                if (a2 < 0) {
                    throw new IOException("retry bulkTransferIn error, ret = " + a2);
                }
            } catch (InterruptedException unused) {
                throw new IOException("wait reconnect usb device Interrupted.");
            }
        }
        return a2;
    }

    /* access modifiers changed from: public */
    private /* synthetic */ Integer a(int i2, byte[] bArr, int i3) {
        int i4;
        b.b(o, "bulkTransferOut begin,len: " + i2);
        try {
            i4 = UsbNative.b(this.e, this.g, bArr, i3, i2, 0);
        } catch (Exception e2) {
            b.b(o, "bulkTransferOut end, error", e2);
            i4 = 0;
        }
        b.b(o, "bulkTransferOut end, len: " + i4);
        return Integer.valueOf(i4);
    }

    private void a(UsbDeviceConnection usbDeviceConnection) {
        try {
            Method declaredMethod = Class.forName("android.hardware.usb.UsbDeviceConnection").getDeclaredMethod("resetDevice", new Class[0]);
            declaredMethod.setAccessible(true);
            b.a(o, "reset usb connection is " + ((Boolean) declaredMethod.invoke(usbDeviceConnection, new Object[0])).booleanValue());
        } catch (Exception e2) {
            b.b(o, "try to reset usb connection fail.", e2);
        }
    }

    private boolean a() {
        String str;
        b.a(o, "changeToAccessoryMode");
        if (this.c == null) {
            return false;
        }
        if (!f()) {
            str = "Change Accessory Mode getProtocolVersion Fail";
        } else if (!m()) {
            str = "Change Accessory Mode sendIdentityStrings Fail";
        } else if (!n()) {
            str = "Change Accessory Mode startAccessoryMode Fail";
        } else {
            b.a(o, "Change Accessory Mode Success");
            return true;
        }
        b.b(o, str);
        return false;
    }

    private boolean a(UsbDevice usbDevice) {
        b.a(o, "initUsbDevice");
        d();
        if (usbDevice == null) {
            b.b(o, "device is null, initUsbDevice fail");
            return false;
        } else if (this.b == null) {
            b.b(o, "mUsbManager is null, initUsbDevice fail");
            return false;
        } else {
            this.c = usbDevice;
            if (this.h < 40) {
                this.h = 40;
            }
            if (i()) {
                return false;
            }
            if (!j()) {
                if (this.h < 60) {
                    this.h = 60;
                }
                if (a()) {
                    this.m = true;
                    b.d().a(this.c.getProductName());
                    return false;
                }
                int i2 = this.j + 1;
                this.j = i2;
                if (i2 < 10) {
                    return false;
                }
                b.b(o, "can't change to accessory mode");
                b.d().f();
                this.j = 0;
                return true;
            }
            this.j = 0;
            if (this.h < 60) {
                b.d().a(this.c.getProductName());
            }
            if (this.h < 80) {
                this.h = 80;
            }
            if (!this.m && !this.n) {
                a(this.e);
                this.n = true;
            }
            g();
            if (this.h < 100) {
                this.h = 100;
            }
            b.d().i();
            this.h = 0;
            b.a(o, "initUsbDevice success");
            return true;
        }
    }

    private boolean a(UsbDevice usbDevice, Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager == null) {
                b.b(o, "can't get package manager");
                return false;
            }
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 128);
            Method declaredMethod = Class.forName("android.os.ServiceManager").getDeclaredMethod("getService", String.class);
            declaredMethod.setAccessible(true);
            IBinder iBinder = (IBinder) declaredMethod.invoke(null, a.b.a.c.n);
            Class<?> cls = Class.forName("android.hardware.usb.IUsbManager");
            Method declaredMethod2 = Class.forName("android.hardware.usb.IUsbManager$Stub").getDeclaredMethod("asInterface", IBinder.class);
            declaredMethod2.setAccessible(true);
            Object invoke = declaredMethod2.invoke(null, iBinder);
            b.a(o, "UID : " + applicationInfo.uid + " " + applicationInfo.processName + " " + applicationInfo.permission);
            Method declaredMethod3 = cls.getDeclaredMethod("grantDevicePermission", UsbDevice.class, Integer.TYPE);
            declaredMethod3.setAccessible(true);
            declaredMethod3.invoke(invoke, usbDevice, Integer.valueOf(applicationInfo.uid));
            b.a(o, "Method OK : " + iBinder + "  " + invoke);
            return true;
        } catch (Exception e2) {
            b.b(o, "Error trying to assigning automatic usb permission : ", e2);
            return false;
        }
    }

    private int b(byte[] bArr, int i2) {
        try {
            if (this.e == null || this.g == null) {
                throw new IOException("mUsbDeviceConnection or mUsbEndpointIn is null");
            }
            int i3 = 0;
            int i4 = i2;
            int i5 = 0;
            while (true) {
                if (i4 <= 0) {
                    break;
                }
                int b2 = b(bArr, i3, Math.min(i4, 16384));
                if (b2 <= 0) {
                    break;
                }
                i5 = i3 + b2;
                i4 -= b2;
                i3 = i5;
            }
            if (i5 == i2) {
                return i5;
            }
            throw new IOException("Expect send " + i2 + " bytes, but sent " + i5 + " bytes");
        } catch (Exception e2) {
            b.b(o, "bulkTransferOut catch exception" + e2.getMessage(), e2);
            b.d().f();
            return -1;
        }
    }

    /* JADX WARNING: Removed duplicated region for block: B:19:0x0049  */
    private int b(byte[] bArr, int i2, int i3) {
        Integer num;
        Exception e2;
        CompletableFuture<Integer> c2 = c(bArr, i2, i3);
        try {
            num = c2.get(500, TimeUnit.MILLISECONDS);
            if (num == null) {
                return -1;
            }
        } catch (Exception e3) {
            b.b(o, "bulkTransferOut error", e3);
            k();
            try {
                num = c2.get(10, TimeUnit.MILLISECONDS);
                if (num == null) {
                    try {
                        b.b(o, "ret is null after retrieve write result again");
                        num = -1;
                    } catch (Exception e4) {
                        e2 = e4;
                    }
                }
            } catch (Exception e5) {
                num = 0;
                e2 = e5;
                b.a(o, "try get last bulkTransferOut result again error: ", e2);
                if (num.intValue() <= 0) {
                }
                return num.intValue();
            }
        }
        if (num.intValue() <= 0) {
            b.a(o, "retry bulkTransferOut");
            try {
                num = c(bArr, i2, i3).get(500, TimeUnit.MILLISECONDS);
                if (num == null) {
                    return -1;
                }
            } catch (Exception e6) {
                b.b(o, "retry bulkTransferOut error", e6);
                d();
                throw new IOException("retry bulkTransferOut error");
            }
        }
        return num.intValue();
    }

    private void b() {
        UsbDeviceConnection usbDeviceConnection = this.e;
        if (usbDeviceConnection != null) {
            usbDeviceConnection.releaseInterface(this.d);
            this.e.close();
        }
    }

    private boolean b(UsbDevice usbDevice) {
        String str;
        if (!(usbDevice == null || usbDevice.getManufacturerName() == null || usbDevice.getProductName() == null || usbDevice.getSerialNumber() == null)) {
            if (n0.containsKey(Integer.valueOf(usbDevice.getVendorId()))) {
                str = "this device match vendor id";
            } else {
                int i2 = 0;
                while (true) {
                    if (i2 < usbDevice.getInterfaceCount()) {
                        UsbInterface usbInterface = usbDevice.getInterface(i2);
                        if (usbInterface != null) {
                            if (usbDevice.getInterfaceCount() != 1 || i2 != 0 || 8 != usbInterface.getInterfaceClass() || 6 != usbInterface.getInterfaceSubclass() || 80 != usbInterface.getInterfaceProtocol()) {
                                if (6 == usbInterface.getInterfaceClass() && 6 == usbInterface.getInterfaceSubclass() && 1 == usbInterface.getInterfaceProtocol()) {
                                    str = "this device is ptp device";
                                    break;
                                }
                            } else {
                                b.a(o, "this device is storage device, ignore it");
                                return false;
                            }
                        }
                        i2++;
                    } else {
                        for (int i3 = 0; i3 < usbDevice.getConfigurationCount(); i3++) {
                            String name = usbDevice.getConfiguration(i3).getName();
                            if (name != null) {
                                if (Pattern.compile(Pattern.quote(t), 2).matcher(name).find()) {
                                    str = "this device has accessory configuration";
                                } else if (Pattern.compile(Pattern.quote(r), 2).matcher(name).find()) {
                                    str = "this device has adb configuration";
                                } else if (Pattern.compile(Pattern.quote(p), 2).matcher(name).find()) {
                                    str = "this device has mtp configuration";
                                } else if (Pattern.compile(Pattern.quote(q), 2).matcher(name).find()) {
                                    str = "this device has ptp configuration";
                                } else if (Pattern.compile(Pattern.quote(s), 2).matcher(name).find()) {
                                    str = "this device has midi configuration";
                                }
                            }
                        }
                    }
                }
            }
            b.a(o, str);
            return true;
        }
        return false;
    }

    private CompletableFuture<Integer> c(byte[] bArr, int i2, int i3) {
        return CompletableFuture.supplyAsync(new Supplier(i3, bArr, i2) {
            /* class a.c.a.b.$$Lambda$c$tIsQp3IeTHlsClVsFXonGe_8eeA */
            public final /* synthetic */ int f$1;
            public final /* synthetic */ byte[] f$2;
            public final /* synthetic */ int f$3;

            {
                this.f$1 = r2;
                this.f$2 = r3;
                this.f$3 = r4;
            }

            @Override // java.util.function.Supplier
            public final Object get() {
                return c.lambda$tIsQp3IeTHlsClVsFXonGe_8eeA(c.this, this.f$1, this.f$2, this.f$3);
            }
        });
    }

    private void d() {
        b.a(o, "deInitUsbDevice");
        try {
            this.f = null;
            this.g = null;
            this.c = null;
            b();
            this.e = null;
        } catch (Exception e2) {
            b.b(o, "deInitUsbDevice fail", e2);
        }
    }

    public static c e() {
        return l0;
    }

    private boolean f() {
        byte[] bArr = new byte[2];
        if (a(bArr) < 0) {
            b.a(o, "get protocol version fail");
            return false;
        }
        int i2 = bArr[0] | (bArr[1] << 8);
        if (i2 < 1 || i2 > 2) {
            b.b(o, "usb device not capable of AOA 1.0 or 2.0, version = " + i2);
            return false;
        }
        b.a(o, "usb device AOA version is " + i2);
        return true;
    }

    private void g() {
        b.a(o, "get endpoint to read/write");
        this.f = this.d.getEndpoint(0);
        this.g = this.d.getEndpoint(1);
    }

    private boolean i() {
        try {
            this.d = this.c.getInterface(0);
            UsbDeviceConnection openDevice = this.b.openDevice(this.c);
            this.e = openDevice;
            openDevice.claimInterface(this.d, true);
            return false;
        } catch (Exception e2) {
            b.b(o, "initUsbDevice fail", e2);
            d();
            return true;
        }
    }

    private boolean j() {
        b.a(o, "isAccessoryMode");
        UsbDevice usbDevice = this.c;
        boolean z2 = false;
        if (usbDevice == null) {
            return false;
        }
        int vendorId = usbDevice.getVendorId();
        int productId = this.c.getProductId();
        if (vendorId == G && (productId == C || productId == D || productId == E || productId == F)) {
            z2 = true;
        }
        b.a(o, z2 ? "Android device attached in Accessory Mode" : "Android device attached not in Accessory Mode");
        return z2;
    }

    private void k() {
        b.a(o, "reConnectUsbDevice");
        this.l = new CountDownLatch(1);
        b();
        i();
        g();
        this.l.countDown();
    }

    private boolean m() {
        String str;
        if (a(52, 0, M.getBytes(StandardCharsets.UTF_8)) < 0) {
            str = "send identity AOA_MANUFACTURER fail";
        } else if (a(52, 1, N.getBytes(StandardCharsets.UTF_8)) < 0) {
            str = "send identity AOA_MODEL_NAME fail";
        } else if (a(52, 2, O.getBytes(StandardCharsets.UTF_8)) < 0) {
            str = "send identity AOA_DESCRIPTION fail";
        } else if (a(52, 3, P.getBytes(StandardCharsets.UTF_8)) < 0) {
            str = "send identity AOA_VERSION fail";
        } else if (a(52, 4, Q.getBytes(StandardCharsets.UTF_8)) < 0) {
            str = "send identity AOA_URI fail";
        } else if (a(52, 5, this.k.getBytes(StandardCharsets.UTF_8)) < 0) {
            str = "send identity AOA_SERIAL_NUMBER fail";
        } else {
            b.a(o, "send identity string success");
            return true;
        }
        b.a(o, str);
        return false;
    }

    private boolean n() {
        if (a(53, 0, (byte[]) null) < 0) {
            b.a(o, "start accessory mode fail");
            return false;
        }
        b.a(o, "start accessory mode success");
        return true;
    }

    public int a(byte[] bArr, int i2) {
        try {
            if (this.e == null || this.f == null) {
                throw new IOException("mUsbDeviceConnection or mUsbEndpointIn is null");
            }
            int i3 = 0;
            int i4 = i2;
            int i5 = 0;
            while (true) {
                if (i4 <= 0) {
                    break;
                }
                int a2 = a(bArr, i3, Math.min(i4, 16384));
                if (a2 <= 0) {
                    break;
                }
                i5 = i3 + a2;
                i4 -= a2;
                i3 = i5;
            }
            if (i5 != 0) {
                if (i5 != i2) {
                    throw new IOException("Expect bulkTransferIn " + i2 + " bytes, but received " + i5 + " bytes");
                }
            }
            return i5;
        } catch (Exception e2) {
            b.b(o, "bulkTransferIn catch exception " + e2.getMessage(), e2);
            b.d().f();
            return -1;
        }
    }

    public synchronized int a(byte[] bArr, int i2, byte[] bArr2, int i3) {
        if (b(bArr, i2) < 0) {
            b.b(o, "bulkTransferOut fail 1");
            return -1;
        } else if (b(bArr2, i3) < 0) {
            b.b(o, "bulkTransferOut fail 2");
            return -1;
        } else {
            return i2 + i3;
        }
    }

    public void a(Context context, String str, String str2, String str3, String str4, String str5, String str6) {
        b.a(o, "init");
        this.f59a = context;
        this.k = d.a(str2, str, str3, str4, str5, str6);
        this.b = (UsbManager) this.f59a.getSystemService(a.b.a.c.n);
        UsbNative.b(this.f59a.getApplicationInfo().targetSdkVersion);
    }

    public void c() {
        d();
        this.m = false;
        this.n = false;
    }

    public void h() {
        this.h = 0;
        this.j = 0;
        this.i = 0;
    }

    public boolean l() {
        UsbManager usbManager;
        if (this.f59a == null || (usbManager = this.b) == null) {
            b.b(o, "scanUsbDevices fail");
            return false;
        }
        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
        b.a(o, "device count = " + deviceList.size());
        if (deviceList.size() == 0) {
            if (this.h > 0) {
                int i2 = this.i + 1;
                this.i = i2;
                if (i2 < 5) {
                    return false;
                }
                b.a(o, "can't get devices again after change to AOA mode");
                this.i = 0;
                return true;
            }
            this.i = 0;
        }
        for (UsbDevice usbDevice : deviceList.values()) {
            if (usbDevice != null) {
                int vendorId = usbDevice.getVendorId();
                int productId = usbDevice.getProductId();
                b.a(o, "vid = 0x" + a.c.c.b.a(vendorId, 4));
                b.a(o, "pid = 0x" + a.c.c.b.a(productId, 4));
                b.a(o, usbDevice.toString());
                if (!b(usbDevice)) {
                    b.a(o, "ignore non Android device");
                } else if (this.b.hasPermission(usbDevice) || a(usbDevice, this.f59a)) {
                    if (this.h < 20) {
                        this.h = 20;
                    }
                    if (a(usbDevice)) {
                        b.a(o, "init device success");
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
