package com.google.firebase.remoteconfig.internal;

import B.a;
import L4.d;
import L4.e;
import L4.g;
import M4.f;
import M4.h;
import T2.b;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;
import androidx.annotation.Keep;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/* JADX INFO: loaded from: classes.dex */
public class ConfigFetchHttpClient {

    /* JADX INFO: renamed from: h, reason: collision with root package name */
    public static final Pattern f10558h = Pattern.compile("^[^:]+:([0-9]+):(android|ios|web):([0-9a-f]+)");

    /* JADX INFO: renamed from: a, reason: collision with root package name */
    public final Context f10559a;

    /* JADX INFO: renamed from: b, reason: collision with root package name */
    public final String f10560b;

    /* JADX INFO: renamed from: c, reason: collision with root package name */
    public final String f10561c;

    /* JADX INFO: renamed from: d, reason: collision with root package name */
    public final String f10562d;

    /* JADX INFO: renamed from: e, reason: collision with root package name */
    public final String f10563e;

    /* JADX INFO: renamed from: f, reason: collision with root package name */
    public final long f10564f;

    /* JADX INFO: renamed from: g, reason: collision with root package name */
    public final long f10565g;

    public ConfigFetchHttpClient(Context context, String str, String str2, long j8, long j9) {
        this.f10559a = context;
        this.f10560b = str;
        this.f10561c = str2;
        Matcher matcher = f10558h.matcher(str);
        this.f10562d = matcher.matches() ? matcher.group(1) : null;
        this.f10563e = "firebase";
        this.f10564f = j8;
        this.f10565g = j9;
    }

    public static JSONObject c(HttpURLConnection httpURLConnection) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
        StringBuilder sb = new StringBuilder();
        while (true) {
            int i = bufferedReader.read();
            if (i == -1) {
                return new JSONObject(sb.toString());
            }
            sb.append((char) i);
        }
    }

    public static void d(HttpURLConnection httpURLConnection, byte[] bArr) throws IOException {
        httpURLConnection.setFixedLengthStreamingMode(bArr.length);
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(httpURLConnection.getOutputStream());
        bufferedOutputStream.write(bArr);
        bufferedOutputStream.flush();
        bufferedOutputStream.close();
    }

    public final JSONObject a(String str, String str2, Map map, Long l8, Map map2) throws d {
        HashMap map3 = new HashMap();
        if (str == null) {
            throw new d("Fetch failed: Firebase installation id is null.");
        }
        map3.put("appInstanceId", str);
        map3.put("appInstanceIdToken", str2);
        map3.put("appId", this.f10560b);
        Context context = this.f10559a;
        Locale locale = context.getResources().getConfiguration().locale;
        map3.put("countryCode", locale.getCountry());
        int i = Build.VERSION.SDK_INT;
        map3.put("languageCode", locale.toLanguageTag());
        map3.put("platformVersion", Integer.toString(i));
        map3.put("timeZone", TimeZone.getDefault().getID());
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            if (packageInfo != null) {
                map3.put("appVersion", packageInfo.versionName);
                map3.put("appBuild", Long.toString(i >= 28 ? a.b(packageInfo) : packageInfo.versionCode));
            }
        } catch (PackageManager.NameNotFoundException unused) {
        }
        map3.put("packageName", context.getPackageName());
        map3.put("sdkVersion", "22.1.2");
        map3.put("analyticsUserProperties", new JSONObject(map));
        if (!map2.isEmpty()) {
            map3.put("customSignals", new JSONObject(map2));
            Log.d("FirebaseRemoteConfig", "Keys of custom signals during fetch: " + map2.keySet());
        }
        if (l8 != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            map3.put("firstOpenTime", simpleDateFormat.format(l8));
        }
        return new JSONObject(map3);
    }

    public final HttpURLConnection b() {
        try {
            return (HttpURLConnection) new URL("https://firebaseremoteconfig.googleapis.com/v1/projects/" + this.f10562d + "/namespaces/" + this.f10563e + ":fetch").openConnection();
        } catch (IOException e8) {
            throw new e(e8.getMessage());
        }
    }

    /* JADX WARN: Removed duplicated region for block: B:15:0x009f A[LOOP:0: B:13:0x0099->B:15:0x009f, LOOP_END] */
    /* JADX WARN: Removed duplicated region for block: B:19:0x00da A[Catch: all -> 0x01a5, IOException | JSONException -> 0x01a7, IOException -> 0x01a9, TRY_LEAVE, TryCatch #3 {all -> 0x01a5, blocks: (B:17:0x00be, B:19:0x00da, B:70:0x01ab, B:71:0x01b4, B:72:0x01b5, B:73:0x01bc), top: B:89:0x00be }] */
    /* JADX WARN: Removed duplicated region for block: B:70:0x01ab A[Catch: all -> 0x01a5, IOException | JSONException -> 0x01a7, IOException -> 0x01a9, TRY_ENTER, TryCatch #3 {all -> 0x01a5, blocks: (B:17:0x00be, B:19:0x00da, B:70:0x01ab, B:71:0x01b4, B:72:0x01b5, B:73:0x01bc), top: B:89:0x00be }] */
    @Keep
    /*
        Code decompiled incorrectly, please refer to instructions dump.
    */
    public h fetch(HttpURLConnection httpURLConnection, String str, String str2, Map<String, String> map, String str3, Map<String, String> map2, Long l8, Date date, Map<String, String> map3) {
        String strA;
        int responseCode;
        JSONObject jSONObject;
        JSONArray jSONArray;
        JSONObject jSONObject2;
        JSONArray jSONArray2;
        boolean z8;
        byte[] bArrC;
        httpURLConnection.setDoOutput(true);
        TimeUnit timeUnit = TimeUnit.SECONDS;
        httpURLConnection.setConnectTimeout((int) timeUnit.toMillis(this.f10564f));
        httpURLConnection.setReadTimeout((int) timeUnit.toMillis(this.f10565g));
        httpURLConnection.setRequestProperty("If-None-Match", str3);
        httpURLConnection.setRequestProperty("X-Goog-Api-Key", this.f10561c);
        Context context = this.f10559a;
        httpURLConnection.setRequestProperty("X-Android-Package", context.getPackageName());
        try {
            bArrC = b.c(context, context.getPackageName());
        } catch (PackageManager.NameNotFoundException e8) {
            Log.e("FirebaseRemoteConfig", "No such package: " + context.getPackageName(), e8);
        }
        if (bArrC == null) {
            Log.e("FirebaseRemoteConfig", "Could not get fingerprint hash for package: " + context.getPackageName());
            strA = null;
            httpURLConnection.setRequestProperty("X-Android-Cert", strA);
            httpURLConnection.setRequestProperty("X-Google-GFE-Can-Retry", "yes");
            httpURLConnection.setRequestProperty("X-Goog-Firebase-Installations-Auth", str2);
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Accept", "application/json");
            for (Map.Entry<String, String> entry : map2.entrySet()) {
                httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue());
            }
            try {
                try {
                    d(httpURLConnection, a(str, str2, map, l8, map3).toString().getBytes("utf-8"));
                    httpURLConnection.connect();
                    responseCode = httpURLConnection.getResponseCode();
                    if (responseCode == 200) {
                        throw new g(responseCode, httpURLConnection.getResponseMessage());
                    }
                    String headerField = httpURLConnection.getHeaderField("ETag");
                    JSONObject jSONObjectC = c(httpURLConnection);
                    try {
                        httpURLConnection.getInputStream().close();
                    } catch (IOException unused) {
                    }
                    try {
                        M4.e eVarC = f.c();
                        eVarC.f4225b = date;
                        try {
                            jSONObject = jSONObjectC.getJSONObject("entries");
                        } catch (JSONException unused2) {
                            jSONObject = null;
                        }
                        if (jSONObject != null) {
                            try {
                                eVarC.f4224a = new JSONObject(jSONObject.toString());
                            } catch (JSONException unused3) {
                            }
                        }
                        try {
                            jSONArray = jSONObjectC.getJSONArray("experimentDescriptions");
                        } catch (JSONException unused4) {
                            jSONArray = null;
                        }
                        if (jSONArray != null) {
                            try {
                                eVarC.f4226c = new JSONArray(jSONArray.toString());
                            } catch (JSONException unused5) {
                            }
                        }
                        try {
                            jSONObject2 = jSONObjectC.getJSONObject("personalizationMetadata");
                        } catch (JSONException unused6) {
                            jSONObject2 = null;
                        }
                        if (jSONObject2 != null) {
                            try {
                                eVarC.f4227d = new JSONObject(jSONObject2.toString());
                            } catch (JSONException unused7) {
                            }
                        }
                        String string = jSONObjectC.has("templateVersion") ? jSONObjectC.getString("templateVersion") : null;
                        if (string != null) {
                            eVarC.f4228e = Long.parseLong(string);
                        }
                        try {
                            jSONArray2 = jSONObjectC.getJSONArray("rolloutMetadata");
                        } catch (JSONException unused8) {
                            jSONArray2 = null;
                        }
                        if (jSONArray2 != null) {
                            try {
                                eVarC.f4229f = new JSONArray(jSONArray2.toString());
                            } catch (JSONException unused9) {
                            }
                        }
                        f fVar = new f(eVarC.f4224a, eVarC.f4225b, eVarC.f4226c, eVarC.f4227d, eVarC.f4228e, eVarC.f4229f);
                        try {
                            z8 = !jSONObjectC.get("state").equals("NO_CHANGE");
                        } catch (JSONException unused10) {
                            z8 = true;
                        }
                        return !z8 ? new h(1, fVar, null) : new h(0, fVar, headerField);
                    } catch (JSONException e9) {
                        throw new d("Fetch failed: fetch response could not be parsed.", e9);
                    }
                } finally {
                    httpURLConnection.disconnect();
                    try {
                        httpURLConnection.getInputStream().close();
                    } catch (IOException unused11) {
                    }
                }
            } catch (IOException | JSONException e10) {
                throw new d("The client had an error while calling the backend!", e10);
            }
        }
        strA = b.a(bArrC);
        httpURLConnection.setRequestProperty("X-Android-Cert", strA);
        httpURLConnection.setRequestProperty("X-Google-GFE-Can-Retry", "yes");
        httpURLConnection.setRequestProperty("X-Goog-Firebase-Installations-Auth", str2);
        httpURLConnection.setRequestProperty("Content-Type", "application/json");
        httpURLConnection.setRequestProperty("Accept", "application/json");
        while (r0.hasNext()) {
        }
        d(httpURLConnection, a(str, str2, map, l8, map3).toString().getBytes("utf-8"));
        httpURLConnection.connect();
        responseCode = httpURLConnection.getResponseCode();
        if (responseCode == 200) {
        }
    }
}
