package com.pichillilorenzo.flutter_inappwebview_android;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Insets;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.http.SslCertificate;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.WindowInsets;
import android.view.WindowManager;
import android.view.WindowMetrics;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.pichillilorenzo.flutter_inappwebview_android.types.Size2D;
import com.pichillilorenzo.flutter_inappwebview_android.types.SyncBaseCallbackResultImpl;
import defpackage.e;
import ed.u;
import io.flutter.embedding.engine.loader.f;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.Key;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import javax.net.ssl.SSLHandshakeException;
import org.json.JSONArray;
import org.json.JSONObject;
import xyz.stream.api.a0;

/* JADX INFO: loaded from: classes.dex */
public class Util {
    public static final String ANDROID_ASSET_URL = "file:///android_asset/";
    static final String LOG_TAG = "Util";

    public static class PrivateKeyAndCertificates {
        public X509Certificate[] certificates;
        public PrivateKey privateKey;

        public PrivateKeyAndCertificates(PrivateKey privateKey, X509Certificate[] x509CertificateArr) {
            this.privateKey = privateKey;
            this.certificates = x509CertificateArr;
        }
    }

    private Util() {
    }

    @RequiresApi(api = 19)
    public static String JSONStringify(@Nullable Object obj) {
        return obj == null ? "null" : obj instanceof Map ? new JSONObject((Map) obj).toString() : obj instanceof List ? new JSONArray((Collection) obj).toString() : obj instanceof String ? JSONObject.quote((String) obj) : JSONObject.wrap(obj).toString();
    }

    public static Drawable drawableFromBytes(Context context, byte[] bArr) {
        return new BitmapDrawable(context.getResources(), BitmapFactory.decodeByteArray(bArr, 0, bArr.length));
    }

    public static InputStream getFileAsset(InAppWebViewFlutterPlugin inAppWebViewFlutterPlugin, String str) throws IOException {
        f fVar = (f) ((a0) inAppWebViewFlutterPlugin.flutterAssets).f35758b;
        StringBuilder sb = new StringBuilder();
        sb.append(fVar.f27990c.f27976b);
        return inAppWebViewFlutterPlugin.applicationContext.getResources().getAssets().open(e.o(sb, File.separator, str));
    }

    public static Size2D getFullscreenSize(Context context) {
        Size2D size2D = new Size2D(-1.0d, -1.0d);
        WindowManager windowManager = (WindowManager) context.getSystemService("window");
        if (windowManager != null) {
            if (Build.VERSION.SDK_INT >= 30) {
                WindowMetrics currentWindowMetrics = windowManager.getCurrentWindowMetrics();
                Insets insetsIgnoringVisibility = currentWindowMetrics.getWindowInsets().getInsetsIgnoringVisibility(WindowInsets.Type.navigationBars() | WindowInsets.Type.displayCutout());
                int i10 = insetsIgnoringVisibility.left + insetsIgnoringVisibility.right;
                int i11 = insetsIgnoringVisibility.bottom + insetsIgnoringVisibility.top;
                Rect bounds = currentWindowMetrics.getBounds();
                size2D.setWidth(bounds.width() - i10);
                size2D.setHeight(bounds.height() - i11);
            } else {
                windowManager.getDefaultDisplay().getMetrics(new DisplayMetrics());
                size2D.setWidth(r1.widthPixels);
                size2D.setHeight(r1.heightPixels);
            }
        }
        return size2D;
    }

    public static <T> T getOrDefault(Map<String, Object> map, String str, T t10) {
        return map.containsKey(str) ? (T) map.get(str) : t10;
    }

    public static float getPixelDensity(Context context) {
        return context.getResources().getDisplayMetrics().density;
    }

    public static String getUrlAsset(InAppWebViewFlutterPlugin inAppWebViewFlutterPlugin, String str) throws IOException {
        f fVar = (f) ((a0) inAppWebViewFlutterPlugin.flutterAssets).f35758b;
        StringBuilder sb = new StringBuilder();
        sb.append(fVar.f27990c.f27976b);
        String strO = e.o(sb, File.separator, str);
        try {
            InputStream fileAsset = getFileAsset(inAppWebViewFlutterPlugin, str);
            if (fileAsset != null) {
                fileAsset.close();
            }
            e = null;
        } catch (IOException e10) {
            e = e10;
        }
        if (e == null) {
            return e.i(ANDROID_ASSET_URL, strO);
        }
        throw e;
    }

    public static X509Certificate getX509CertFromSslCertHack(SslCertificate sslCertificate) {
        byte[] byteArray = SslCertificate.saveState(sslCertificate).getByteArray("x509-certificate");
        if (byteArray == null) {
            return null;
        }
        try {
            return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(byteArray));
        } catch (CertificateException unused) {
            return null;
        }
    }

    public static <T> T invokeMethodAndWaitResult(@NonNull final u uVar, @NonNull final String str, @Nullable final Object obj, @NonNull final SyncBaseCallbackResultImpl<T> syncBaseCallbackResultImpl) throws InterruptedException {
        new Handler(Looper.getMainLooper()).post(new Runnable() { // from class: com.pichillilorenzo.flutter_inappwebview_android.Util.1
            @Override // java.lang.Runnable
            public void run() {
                uVar.invokeMethod(str, obj, syncBaseCallbackResultImpl);
            }
        });
        syncBaseCallbackResultImpl.latch.await();
        return syncBaseCallbackResultImpl.result;
    }

    @Nullable
    public static <O> Object invokeMethodIfExists(O o10, String str, Object... objArr) {
        for (Method method : o10.getClass().getMethods()) {
            if (method.getName().equals(str)) {
                try {
                    return method.invoke(o10, objArr);
                } catch (IllegalAccessException | InvocationTargetException unused) {
                    return null;
                }
            }
        }
        return null;
    }

    public static boolean isClass(String str) {
        try {
            Class.forName(str);
            return true;
        } catch (ClassNotFoundException unused) {
            return false;
        }
    }

    public static boolean isIPv6(String str) {
        try {
            InetAddress.getByName(str);
            return true;
        } catch (UnknownHostException unused) {
            return false;
        }
    }

    @Nullable
    public static PrivateKeyAndCertificates loadPrivateKeyAndCertificate(@NonNull InAppWebViewFlutterPlugin inAppWebViewFlutterPlugin, @NonNull String str, @Nullable String str2, @NonNull String str3) {
        InputStream fileInputStream;
        try {
            fileInputStream = getFileAsset(inAppWebViewFlutterPlugin, str);
        } catch (IOException unused) {
            fileInputStream = null;
        }
        if (fileInputStream == null) {
            try {
                fileInputStream = new FileInputStream(str);
            } catch (Exception unused2) {
                if (fileInputStream != null) {
                }
                return privateKeyAndCertificates;
            } catch (Throwable th) {
                if (fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException unused3) {
                    }
                }
                throw th;
            }
        }
        KeyStore keyStore = KeyStore.getInstance(str3);
        keyStore.load(fileInputStream, (str2 != null ? str2 : "").toCharArray());
        String strNextElement = keyStore.aliases().nextElement();
        if (str2 == null) {
            str2 = "";
        }
        Key key = keyStore.getKey(strNextElement, str2.toCharArray());
        privateKeyAndCertificates = key instanceof PrivateKey ? new PrivateKeyAndCertificates((PrivateKey) key, new X509Certificate[]{(X509Certificate) keyStore.getCertificate(strNextElement)}) : null;
        fileInputStream.close();
        try {
            fileInputStream.close();
        } catch (IOException unused4) {
        }
        return privateKeyAndCertificates;
    }

    public static void log(String str, String str2) {
        int iMin;
        int length = str2.length();
        int i10 = 0;
        while (i10 < length) {
            int iIndexOf = str2.indexOf(10, i10);
            if (iIndexOf == -1) {
                iIndexOf = length;
            }
            while (true) {
                iMin = Math.min(iIndexOf, i10 + 4000);
                str2.substring(i10, iMin);
                if (iMin >= iIndexOf) {
                    break;
                } else {
                    i10 = iMin;
                }
            }
            i10 = iMin + 1;
        }
    }

    @Nullable
    public static HttpURLConnection makeHttpRequest(String str, String str2, @Nullable Map<String, String> map) {
        HttpURLConnection httpURLConnection;
        try {
            httpURLConnection = (HttpURLConnection) new URL(str).openConnection();
        } catch (Exception e10) {
            e = e10;
            httpURLConnection = null;
        }
        try {
            httpURLConnection.setRequestMethod(str2);
            if (map != null) {
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            httpURLConnection.setConnectTimeout(15000);
            httpURLConnection.setReadTimeout(15000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setInstanceFollowRedirects(true);
            if ("GET".equalsIgnoreCase(str2)) {
                httpURLConnection.setDoOutput(false);
            }
            httpURLConnection.connect();
            return httpURLConnection;
        } catch (Exception e11) {
            e = e11;
            boolean z10 = e instanceof SSLHandshakeException;
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
            return null;
        }
    }

    public static String normalizeIPv6(String str) throws Exception {
        if (isIPv6(str)) {
            return InetAddress.getByName(str).getCanonicalHostName();
        }
        throw new Exception(e.i("Invalid address: ", str));
    }

    public static boolean objEquals(@Nullable Object obj, @Nullable Object obj2) {
        return Objects.equals(obj, obj2);
    }

    /* JADX WARN: Can't wrap try/catch for region: R(8:5|(5:6|46|7|(1:9)(1:48)|29)|14|36|15|38|16|29) */
    @Nullable
    /*
        Code decompiled incorrectly, please refer to instructions dump.
    */
    public static byte[] readAllBytes(@Nullable InputStream inputStream) {
        byte[] byteArray = null;
        if (inputStream == null) {
            return null;
        }
        byte[] bArr = new byte[4096];
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        while (true) {
            try {
                int i10 = inputStream.read(bArr, 0, 4096);
                if (i10 == -1) {
                    break;
                }
                byteArrayOutputStream.write(bArr, 0, i10);
            } catch (IOException e10) {
                try {
                    inputStream.close();
                } catch (IOException e11) {
                    e10.addSuppressed(e11);
                }
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e12) {
                    e10.addSuppressed(e12);
                }
            } catch (Throwable th) {
                try {
                    inputStream.close();
                } catch (IOException unused) {
                }
                try {
                    byteArrayOutputStream.close();
                    throw th;
                } catch (IOException unused2) {
                    throw th;
                }
            }
            return byteArray;
        }
        byteArray = byteArrayOutputStream.toByteArray();
        inputStream.close();
        byteArrayOutputStream.close();
        return byteArray;
    }

    public static String replaceAll(String str, String str2, String str3) {
        return TextUtils.join(str3, str.split(Pattern.quote(str2)));
    }
}
