package com.ifpdos.udi.sdk;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.util.Log;
import com.ifpdos.udi.sdk.UdiSdk;
import com.ifpdos.udi.sdk.binderhttpd.BinderEventHelper;
import com.ifpdos.udi.sdk.binderhttpd.BinderHttpdInterceptor;
import com.ifpdos.udi.sdk.binderhttpd.FixLastArrayList;
import com.ifpdos.udi.sdk.localhttpd.LocalSocketDns;
import com.ifpdos.udi.sdk.localhttpd.LocalSocketEventHelper;
import com.ifpdos.udi.sdk.localhttpd.LocalSocketFactory;
import g.f.b.a.a.b;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import javax.net.ssl.SSLSocketFactory;
import kotlin.collections.EmptyMap;
import kotlin.collections.j;
import kotlin.jvm.internal.o;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.n0.c;

/* JADX INFO: loaded from: classes.dex */
public class UdiSdkEnvironment {
    private static final String PACKAGE_UDI_NO_OPENSDK = "com.ifpdos.udi.server";
    private static final String PACKAGE_UDI_OPENSDK = "com.seewo.mcuservice";
    public static final String TAG = "UdiSdk";
    private b mBinderSocketDns;
    private IEventHelper mEventHelper;
    private UdiSdk.IOkHttpClientBuilderInterceptor mInterceptor;
    private boolean mIsSupportBinderHttpd;
    private String mPackage;
    private IConnectCallback mSseConnectCallback;
    private String mToken;
    private UdiStartMonitor mUdiStartMonitor;
    private Map<IEventHandler, Set<String>> mDelayToRegister = new HashMap();
    private boolean mSseConnectCreate = false;
    private boolean mSuccess = false;
    private IDependentFactory mDependentFactory = new DefaultDependentFactory();

    public static class DefaultDependentFactory implements IDependentFactory {
        private DefaultDependentFactory() {
        }

        @Override // com.ifpdos.udi.sdk.UdiSdkEnvironment.IDependentFactory
        public b buildBinderSocketDns(Context context) {
            return new b(context.getApplicationContext());
        }
    }

    public interface IDependentFactory {
        b buildBinderSocketDns(Context context);
    }

    public class TokenInterceptor implements Interceptor {
        public TokenInterceptor() {
        }

        @Override // okhttp3.Interceptor
        public Response intercept(Interceptor.a aVar) {
            LinkedHashMap linkedHashMap;
            Map mapUnmodifiableMap;
            Request requestE = aVar.getF9829e();
            String strB = requestE.b("invoker");
            if (strB == null) {
                strB = UdiSdkEnvironment.this.mPackage;
            }
            if (UdiSdkEnvironment.this.mToken != null) {
                o.f(requestE, "request");
                new LinkedHashMap();
                HttpUrl httpUrl = requestE.a;
                String str = requestE.f9621b;
                RequestBody requestBody = requestE.f9623d;
                if (requestE.f9624e.isEmpty()) {
                    linkedHashMap = new LinkedHashMap();
                } else {
                    Map<Class<?>, Object> map = requestE.f9624e;
                    o.f(map, "<this>");
                    linkedHashMap = new LinkedHashMap(map);
                }
                Headers.a aVarD = requestE.f9622c.d();
                String str2 = UdiSdkEnvironment.this.mToken;
                o.f("token", "name");
                o.f(str2, "value");
                Objects.requireNonNull(aVarD);
                o.f("token", "name");
                o.f(str2, "value");
                Headers.b bVar = Headers.f10085f;
                bVar.a("token");
                bVar.b(str2, "token");
                aVarD.a("token", str2);
                o.f("invoker", "name");
                o.f(strB, "value");
                Objects.requireNonNull(aVarD);
                o.f("invoker", "name");
                o.f(strB, "value");
                Headers.b bVar2 = Headers.f10085f;
                bVar2.a("invoker");
                bVar2.b(strB, "invoker");
                aVarD.a("invoker", strB);
                if (httpUrl == null) {
                    throw new IllegalStateException("url == null".toString());
                }
                Headers headersB = aVarD.b();
                byte[] bArr = c.a;
                o.f(linkedHashMap, "<this>");
                if (linkedHashMap.isEmpty()) {
                    j.o();
                    mapUnmodifiableMap = EmptyMap.f9308f;
                } else {
                    mapUnmodifiableMap = Collections.unmodifiableMap(new LinkedHashMap(linkedHashMap));
                    o.e(mapUnmodifiableMap, "{\n    Collections.unmodi…(LinkedHashMap(this))\n  }");
                }
                requestE = new Request(httpUrl, str, headersB, requestBody, mapUnmodifiableMap);
            }
            return aVar.a(requestE);
        }
    }

    private synchronized IEventHelper getEventHelper() {
        IEventHelper localSocketEventHelper;
        IEventHelper iEventHelper = this.mEventHelper;
        if (iEventHelper != null) {
            iEventHelper.setToken(this.mToken);
            return this.mEventHelper;
        }
        IConnectCallback iConnectCallback = new IConnectCallback() { // from class: com.ifpdos.udi.sdk.UdiSdkEnvironment.2
            @Override // com.ifpdos.udi.sdk.IConnectCallback
            public void onDisconnect(Exception exc) {
                Log.e("UdiSdk", "sse connect onDisconnect", exc);
                Map<IEventHandler, Set<String>> handlerMap = UdiSdkEnvironment.this.mEventHelper.getHandlerMap();
                UdiSdkEnvironment.this.mEventHelper = null;
                UdiSdkEnvironment.this.mSseConnectCreate = false;
                if (UdiSdkEnvironment.this.mSseConnectCallback != null) {
                    UdiSdkEnvironment.this.mSseConnectCallback.onDisconnect(exc);
                }
                UdiSdkEnvironment.this.reconnectSse(handlerMap);
                UdiSdkEnvironment.this.mSuccess = false;
            }

            @Override // com.ifpdos.udi.sdk.IConnectCallback
            public void onFailed() {
                Log.d("UdiSdk", "sse connect onFailed");
                if (UdiSdkEnvironment.this.mSseConnectCallback != null) {
                    UdiSdkEnvironment.this.mSseConnectCallback.onFailed();
                }
            }

            @Override // com.ifpdos.udi.sdk.IConnectCallback
            public void onSuccess() {
                Log.d("UdiSdk", "sse connect onSuccess");
                UdiSdkEnvironment.this.onSseConnectCreate();
                if (UdiSdkEnvironment.this.mSuccess || UdiSdkEnvironment.this.mSseConnectCallback == null) {
                    return;
                }
                UdiSdkEnvironment.this.mSuccess = true;
                UdiSdkEnvironment.this.mSseConnectCallback.onSuccess();
            }
        };
        if (this.mIsSupportBinderHttpd) {
            localSocketEventHelper = new BinderEventHelper(this.mBinderSocketDns, iConnectCallback);
            this.mEventHelper = localSocketEventHelper;
        } else {
            localSocketEventHelper = new LocalSocketEventHelper(iConnectCallback);
            this.mEventHelper = localSocketEventHelper;
        }
        localSocketEventHelper.start();
        this.mEventHelper.setToken(this.mToken);
        return this.mEventHelper;
    }

    private Set<String> getEventsForHandler(IEventHandler iEventHandler) {
        if (!this.mDelayToRegister.containsKey(iEventHandler)) {
            this.mDelayToRegister.put(iEventHandler, new HashSet());
        }
        return this.mDelayToRegister.get(iEventHandler);
    }

    private IBinder getSystemServer(String str) {
        try {
            return (IBinder) Class.forName("android.os.ServiceManager").getMethod("getService", String.class).invoke(null, str);
        } catch (Exception e2) {
            Log.d("UdiSdk", "getService failed", e2);
            return null;
        }
    }

    private boolean isAppInstalled(Context context, String str) {
        PackageInfo packageInfo;
        if (str == null || str.isEmpty()) {
            return false;
        }
        try {
            packageInfo = context.getPackageManager().getPackageInfo(str, 0);
        } catch (PackageManager.NameNotFoundException unused) {
            packageInfo = null;
        }
        return packageInfo != null;
    }

    private boolean isUdiSupportBinderHttpd() {
        return SystemPropertiesUtils.getBoolean(UdiSdk.PROP_UDI_BINDER_ENABLE, false) || SystemPropertiesUtils.getBoolean(UdiSdk.PROP_UDI_BINDER_ENABLE_SELINUX, false) || getSystemServer(UdiSdk.HOST) != null;
    }

    private OkHttpClient.a newBinderClientBuilder() {
        OkHttpClient.a aVar = new OkHttpClient.a();
        aVar.a(new TokenInterceptor());
        aVar.a(new BinderHttpdInterceptor(this.mBinderSocketDns));
        try {
            replaceBinderHttpdInterceptorList(aVar);
        } catch (Exception e2) {
            Log.e("UdiSdk", "replaceBinderHttpdInterceptorList failed", e2);
        }
        UdiSdk.IOkHttpClientBuilderInterceptor iOkHttpClientBuilderInterceptor = this.mInterceptor;
        return iOkHttpClientBuilderInterceptor != null ? iOkHttpClientBuilderInterceptor.adapt(aVar) : aVar;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public synchronized void onSseConnectCreate() {
        this.mSseConnectCreate = true;
        for (Map.Entry<IEventHandler, Set<String>> entry : this.mDelayToRegister.entrySet()) {
            if (!entry.getValue().isEmpty()) {
                getEventHelper().registerEvents(entry.getValue(), entry.getKey());
            }
        }
        this.mDelayToRegister.clear();
    }

    /* JADX INFO: Access modifiers changed from: private */
    public synchronized void reconnectSse(Map<IEventHandler, Set<String>> map) {
        for (Map.Entry<IEventHandler, Set<String>> entry : map.entrySet()) {
            registerEvents(entry.getValue(), entry.getKey());
        }
    }

    private static void replaceBinderHttpdInterceptorList(OkHttpClient.a aVar) throws IllegalAccessException {
        List list;
        Field[] declaredFields = aVar.getClass().getDeclaredFields();
        for (int i2 = 0; i2 < declaredFields.length; i2++) {
            declaredFields[i2].setAccessible(true);
            if ((declaredFields[i2].get(aVar) instanceof List) && (list = (List) declaredFields[i2].get(aVar)) != null && !list.isEmpty() && (list.get(0) instanceof TokenInterceptor)) {
                FixLastArrayList fixLastArrayList = new FixLastArrayList();
                declaredFields[i2].set(aVar, fixLastArrayList);
                Iterator it = list.iterator();
                while (it.hasNext()) {
                    fixLastArrayList.addToLast((Interceptor) it.next());
                }
            }
        }
    }

    public synchronized void destroy() {
        IEventHelper iEventHelper = this.mEventHelper;
        if (iEventHelper != null) {
            iEventHelper.destroy();
            this.mEventHelper = null;
            this.mSseConnectCreate = false;
        }
        this.mBinderSocketDns = null;
        this.mSuccess = false;
    }

    public void init(Context context, String str) {
        init(context, str, null);
    }

    public void init(Context context, String str, final IConnectCallback iConnectCallback) {
        Log.d("UdiSdk", "start udi client sdk init");
        this.mToken = str;
        this.mPackage = context.getPackageName();
        this.mSseConnectCallback = iConnectCallback;
        boolean zIsAppInstalled = isAppInstalled(context, PACKAGE_UDI_OPENSDK);
        boolean zIsAppInstalled2 = isAppInstalled(context, PACKAGE_UDI_NO_OPENSDK);
        if (!zIsAppInstalled && !zIsAppInstalled2) {
            Log.d("UdiSdk", "com.seewo.mcuservice and com.ifpdos.udi.server init failed");
            if (iConnectCallback != null) {
                iConnectCallback.onFailed();
                return;
            }
            return;
        }
        boolean zIsUdiSupportBinderHttpd = isUdiSupportBinderHttpd();
        this.mIsSupportBinderHttpd = zIsUdiSupportBinderHttpd;
        if (zIsUdiSupportBinderHttpd && this.mBinderSocketDns == null) {
            this.mBinderSocketDns = this.mDependentFactory.buildBinderSocketDns(context.getApplicationContext());
            b.InterfaceC0066b interfaceC0066b = iConnectCallback != null ? new b.InterfaceC0066b() { // from class: com.ifpdos.udi.sdk.UdiSdkEnvironment.1
                @Override // g.f.b.a.a.b.InterfaceC0066b
                public void onServerAvailable(String str2, String str3) {
                    if (UdiSdkEnvironment.this.mSuccess) {
                        return;
                    }
                    UdiSdkEnvironment.this.mSuccess = true;
                    iConnectCallback.onSuccess();
                }
            } : null;
            if (zIsAppInstalled2) {
                this.mBinderSocketDns.a(UdiSdk.HOST, PACKAGE_UDI_NO_OPENSDK, interfaceC0066b);
            } else if (zIsAppInstalled) {
                this.mBinderSocketDns.a(UdiSdk.HOST, PACKAGE_UDI_OPENSDK, interfaceC0066b);
            }
        } else {
            this.mSuccess = true;
            if (iConnectCallback != null) {
                iConnectCallback.onSuccess();
            }
        }
        if (this.mUdiStartMonitor == null) {
            this.mUdiStartMonitor = new UdiStartMonitor(context);
        }
    }

    public OkHttpClient.a newLocalSocketClientBuilder() {
        OkHttpClient.a aVar = new OkHttpClient.a();
        LocalSocketFactory localSocketFactory = new LocalSocketFactory();
        o.f(localSocketFactory, "socketFactory");
        if (!(!(localSocketFactory instanceof SSLSocketFactory))) {
            throw new IllegalArgumentException("socketFactory instanceof SSLSocketFactory".toString());
        }
        if (!o.a(localSocketFactory, aVar.f9586m)) {
            aVar.f9598y = null;
        }
        o.f(localSocketFactory, "<set-?>");
        aVar.f9586m = localSocketFactory;
        LocalSocketDns localSocketDns = new LocalSocketDns();
        o.f(localSocketDns, "dns");
        if (!o.a(localSocketDns, aVar.f9584k)) {
            aVar.f9598y = null;
        }
        o.f(localSocketDns, "<set-?>");
        aVar.f9584k = localSocketDns;
        aVar.a(new TokenInterceptor());
        UdiSdk.IOkHttpClientBuilderInterceptor iOkHttpClientBuilderInterceptor = this.mInterceptor;
        return iOkHttpClientBuilderInterceptor != null ? iOkHttpClientBuilderInterceptor.adapt(aVar) : aVar;
    }

    public OkHttpClient.a newOkHttpClientBuilder() {
        if (this.mToken == null) {
            Log.e("UdiSdk", "a request was called before udi init, and this request call failed");
        }
        return this.mIsSupportBinderHttpd ? newBinderClientBuilder() : newLocalSocketClientBuilder();
    }

    public synchronized void registerEvents(List<String> list, IEventHandler iEventHandler) {
        registerEvents(new HashSet(list), iEventHandler);
    }

    public synchronized void registerEvents(Set<String> set, IEventHandler iEventHandler) {
        if (iEventHandler == null) {
            Log.e("UdiSdk", "can not register null handler for events!", new Exception());
            return;
        }
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            Log.d("UdiSdk", "register  " + it.next() + " for " + iEventHandler);
        }
        IEventHelper eventHelper = getEventHelper();
        if (this.mSseConnectCreate) {
            eventHelper.registerEvents(set, iEventHandler);
        } else {
            getEventsForHandler(iEventHandler).addAll(set);
        }
    }

    public void setDependentFactory(IDependentFactory iDependentFactory) {
        this.mDependentFactory = iDependentFactory;
    }

    public void setOkHttpClientBuilderInterceptor(UdiSdk.IOkHttpClientBuilderInterceptor iOkHttpClientBuilderInterceptor) {
        this.mInterceptor = iOkHttpClientBuilderInterceptor;
    }

    public synchronized void unregisterEvents(IEventHandler iEventHandler) {
        Log.d("UdiSdk", "unregisterEvents all event for " + iEventHandler);
        IEventHelper eventHelper = getEventHelper();
        if (this.mSseConnectCreate) {
            eventHelper.unregisterEvents(iEventHandler);
        } else {
            getEventsForHandler(iEventHandler).clear();
        }
    }

    public synchronized void unregisterEvents(List<String> list, IEventHandler iEventHandler) {
        unregisterEvents(new HashSet(list), iEventHandler);
    }

    public synchronized void unregisterEvents(Set<String> set, IEventHandler iEventHandler) {
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            Log.d("UdiSdk", "unregister  " + it.next() + " for " + iEventHandler);
        }
        IEventHelper eventHelper = getEventHelper();
        if (this.mSseConnectCreate) {
            eventHelper.unregisterEvents(set, iEventHandler);
        } else {
            getEventsForHandler(iEventHandler).removeAll(set);
        }
    }
}
