package m4;

import com.revenuecat.purchases.common.Constants;
import com.revenuecat.purchases.common.diagnostics.DiagnosticsEntry;
import g4.C2066a;
import java.io.IOException;
import java.io.StringReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import k4.AbstractC2384C;
import k4.AbstractC2395h;
import k4.C2411y;

/* JADX INFO: loaded from: classes3.dex */
public final class U extends AbstractC2384C {

    /* JADX INFO: renamed from: s, reason: collision with root package name */
    public static final Logger f20847s;

    /* JADX INFO: renamed from: t, reason: collision with root package name */
    public static final Set f20848t;

    /* JADX INFO: renamed from: u, reason: collision with root package name */
    public static final boolean f20849u;

    /* JADX INFO: renamed from: v, reason: collision with root package name */
    public static final boolean f20850v;

    /* JADX INFO: renamed from: w, reason: collision with root package name */
    public static final boolean f20851w;

    /* JADX INFO: renamed from: x, reason: collision with root package name */
    public static String f20852x;

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

    /* JADX INFO: renamed from: b, reason: collision with root package name */
    public final Random f20854b = new Random();

    /* JADX INFO: renamed from: c, reason: collision with root package name */
    public volatile S f20855c = S.f20756a;

    /* JADX INFO: renamed from: d, reason: collision with root package name */
    public final AtomicReference f20856d = new AtomicReference();

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

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

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

    /* JADX INFO: renamed from: h, reason: collision with root package name */
    public final i2 f20860h;

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

    /* JADX INFO: renamed from: j, reason: collision with root package name */
    public final k4.w0 f20862j;

    /* JADX INFO: renamed from: k, reason: collision with root package name */
    public final E3.p f20863k;
    public boolean l;

    /* JADX INFO: renamed from: m, reason: collision with root package name */
    public boolean f20864m;

    /* JADX INFO: renamed from: n, reason: collision with root package name */
    public Executor f20865n;

    /* JADX INFO: renamed from: o, reason: collision with root package name */
    public final boolean f20866o;

    /* JADX INFO: renamed from: p, reason: collision with root package name */
    public final V1 f20867p;

    /* JADX INFO: renamed from: q, reason: collision with root package name */
    public boolean f20868q;

    /* JADX INFO: renamed from: r, reason: collision with root package name */
    public AbstractC2395h f20869r;

    static {
        Logger logger = Logger.getLogger(U.class.getName());
        f20847s = logger;
        f20848t = Collections.unmodifiableSet(new HashSet(Arrays.asList("clientLanguage", "percentage", "clientHostname", "serviceConfig")));
        String property = System.getProperty("io.grpc.internal.DnsNameResolverProvider.enable_jndi", "true");
        String property2 = System.getProperty("io.grpc.internal.DnsNameResolverProvider.enable_jndi_localhost", "false");
        String property3 = System.getProperty("io.grpc.internal.DnsNameResolverProvider.enable_service_config", "false");
        f20849u = Boolean.parseBoolean(property);
        f20850v = Boolean.parseBoolean(property2);
        f20851w = Boolean.parseBoolean(property3);
        try {
            try {
                try {
                    if (Class.forName("m4.v0", true, U.class.getClassLoader()).asSubclass(T.class).getConstructor(new Class[0]).newInstance(new Object[0]) == null) {
                        throw null;
                    }
                    throw new ClassCastException();
                } catch (Exception e6) {
                    logger.log(Level.FINE, "Can't construct JndiResourceResolverFactory, skipping.", (Throwable) e6);
                }
            } catch (Exception e7) {
                logger.log(Level.FINE, "Can't find JndiResourceResolverFactory ctor, skipping.", (Throwable) e7);
            }
        } catch (ClassCastException e8) {
            logger.log(Level.FINE, "Unable to cast JndiResourceResolverFactory, skipping.", (Throwable) e8);
        } catch (ClassNotFoundException e9) {
            logger.log(Level.FINE, "Unable to find JndiResourceResolverFactory, skipping.", (Throwable) e9);
        }
    }

    public U(String str, k4.j0 j0Var, i2 i2Var, E3.p pVar, boolean z6) {
        A4.g.o(j0Var, "args");
        this.f20860h = i2Var;
        A4.g.o(str, DiagnosticsEntry.NAME_KEY);
        URI uriCreate = URI.create("//".concat(str));
        A4.g.j(str, "Invalid DNS name: %s", uriCreate.getHost() != null);
        String authority = uriCreate.getAuthority();
        if (authority == null) {
            throw new NullPointerException(L4.a.X("nameUri (%s) doesn't have an authority", uriCreate));
        }
        this.f20857e = authority;
        this.f20858f = uriCreate.getHost();
        if (uriCreate.getPort() == -1) {
            this.f20859g = j0Var.f19884a;
        } else {
            this.f20859g = uriCreate.getPort();
        }
        C2549u1 c2549u1 = j0Var.f19885b;
        A4.g.o(c2549u1, "proxyDetector");
        this.f20853a = c2549u1;
        long nanos = 0;
        if (!z6) {
            String property = System.getProperty("networkaddress.cache.ttl");
            long j4 = 30;
            if (property != null) {
                try {
                    j4 = Long.parseLong(property);
                } catch (NumberFormatException unused) {
                    f20847s.log(Level.WARNING, "Property({0}) valid is not valid number format({1}), fall back to default({2})", new Object[]{"networkaddress.cache.ttl", property, 30L});
                }
            }
            nanos = j4 > 0 ? TimeUnit.SECONDS.toNanos(j4) : j4;
        }
        this.f20861i = nanos;
        this.f20863k = pVar;
        k4.w0 w0Var = j0Var.f19886c;
        A4.g.o(w0Var, "syncContext");
        this.f20862j = w0Var;
        J0 j02 = j0Var.f19890g;
        this.f20865n = j02;
        this.f20866o = j02 == null;
        V1 v12 = j0Var.f19887d;
        A4.g.o(v12, "serviceConfigParser");
        this.f20867p = v12;
    }

    public static Map t(Map map, Random random, String str) {
        for (Map.Entry entry : map.entrySet()) {
            android.support.v4.media.session.b.P(entry, "Bad key: %s", f20848t.contains(entry.getKey()));
        }
        List listD = AbstractC2557x0.d("clientLanguage", map);
        if (listD != null && !listD.isEmpty()) {
            Iterator it = listD.iterator();
            while (it.hasNext()) {
                if ("java".equalsIgnoreCase((String) it.next())) {
                }
            }
            return null;
        }
        Double dE = AbstractC2557x0.e("percentage", map);
        if (dE != null) {
            int iIntValue = dE.intValue();
            android.support.v4.media.session.b.P(dE, "Bad percentage: %s", iIntValue >= 0 && iIntValue <= 100);
            if (random.nextInt(100) >= iIntValue) {
                return null;
            }
        }
        List listD2 = AbstractC2557x0.d("clientHostname", map);
        if (listD2 != null && !listD2.isEmpty()) {
            Iterator it2 = listD2.iterator();
            while (it2.hasNext()) {
                if (((String) it2.next()).equals(str)) {
                }
            }
            return null;
        }
        Map mapG = AbstractC2557x0.g("serviceConfig", map);
        if (mapG != null) {
            return mapG;
        }
        throw new E3.v(String.format("key '%s' missing in '%s'", map, "serviceConfig"));
    }

    public static ArrayList u() {
        List<String> list = Collections.EMPTY_LIST;
        ArrayList arrayList = new ArrayList();
        for (String str : list) {
            if (str.startsWith("grpc_config=")) {
                String strSubstring = str.substring(12);
                Logger logger = AbstractC2554w0.f21207a;
                C2066a c2066a = new C2066a(new StringReader(strSubstring));
                try {
                    Object objA = AbstractC2554w0.a(c2066a);
                    if (!(objA instanceof List)) {
                        throw new ClassCastException("wrong type " + objA);
                    }
                    List list2 = (List) objA;
                    AbstractC2557x0.a(list2);
                    arrayList.addAll(list2);
                } finally {
                    try {
                        c2066a.close();
                    } catch (IOException e6) {
                        logger.log(Level.WARNING, "Failed to close", (Throwable) e6);
                    }
                }
            } else {
                f20847s.log(Level.FINE, "Ignoring non service config {0}", new Object[]{str});
            }
        }
        return arrayList;
    }

    @Override // k4.AbstractC2384C
    public final String k() {
        return this.f20857e;
    }

    @Override // k4.AbstractC2384C
    public final void m() {
        A4.g.t(this.f20869r != null, "not started");
        v();
    }

    @Override // k4.AbstractC2384C
    public final void o() {
        if (this.f20864m) {
            return;
        }
        this.f20864m = true;
        Executor executor = this.f20865n;
        if (executor == null || !this.f20866o) {
            return;
        }
        f2.b(this.f20860h, executor);
        this.f20865n = null;
    }

    @Override // k4.AbstractC2384C
    public final void p(AbstractC2395h abstractC2395h) {
        A4.g.t(this.f20869r == null, "already started");
        if (this.f20866o) {
            this.f20865n = (Executor) f2.a(this.f20860h);
        }
        this.f20869r = abstractC2395h;
        v();
    }

    public final C4.f s() {
        k4.k0 k0Var;
        k4.k0 k0Var2;
        List listV;
        k4.k0 k0Var3;
        String str = this.f20858f;
        C4.f fVar = new C4.f(27, false);
        try {
            fVar.f742c = w();
            if (f20851w) {
                List list = Collections.EMPTY_LIST;
                boolean z6 = false;
                if (f20849u) {
                    if ("localhost".equalsIgnoreCase(str)) {
                        z6 = f20850v;
                    } else if (!str.contains(Constants.SUBS_ID_BASE_PLAN_ID_SEPARATOR)) {
                        boolean z7 = true;
                        for (int i6 = 0; i6 < str.length(); i6++) {
                            char cCharAt = str.charAt(i6);
                            if (cCharAt != '.') {
                                z7 &= cCharAt >= '0' && cCharAt <= '9';
                            }
                        }
                        z6 = !z7;
                    }
                }
                if (z6 && this.f20856d.get() != null) {
                    throw new ClassCastException();
                }
                Object k0Var4 = null;
                if (list.isEmpty()) {
                    f20847s.log(Level.FINE, "No TXT records found for {0}", new Object[]{str});
                } else {
                    Random random = this.f20854b;
                    if (f20852x == null) {
                        try {
                            f20852x = InetAddress.getLocalHost().getHostName();
                        } catch (UnknownHostException e6) {
                            throw new RuntimeException(e6);
                        }
                    }
                    String str2 = f20852x;
                    try {
                        Iterator it = u().iterator();
                        Map mapT = null;
                        while (it.hasNext()) {
                            try {
                                mapT = t((Map) it.next(), random, str2);
                                if (mapT != null) {
                                    break;
                                }
                            } catch (RuntimeException e7) {
                                k0Var = new k4.k0(k4.r0.f19940g.g("failed to pick service config choice").f(e7));
                            }
                        }
                        k0Var = mapT == null ? null : new k4.k0(mapT);
                    } catch (IOException | RuntimeException e8) {
                        k0Var = new k4.k0(k4.r0.f19940g.g("failed to parse TXT records").f(e8));
                    }
                    if (k0Var != null) {
                        k4.r0 r0Var = k0Var.f19891a;
                        if (r0Var != null) {
                            k0Var4 = new k4.k0(r0Var);
                        } else {
                            Map map = (Map) k0Var.f19892b;
                            V1 v12 = this.f20867p;
                            v12.getClass();
                            try {
                                k2 k2Var = (k2) v12.f20889d;
                                k2Var.getClass();
                                if (map != null) {
                                    try {
                                        listV = c2.v(c2.q(map));
                                    } catch (RuntimeException e9) {
                                        k0Var3 = new k4.k0(k4.r0.f19940g.g("can't parse load balancer configuration").f(e9));
                                    }
                                } else {
                                    listV = null;
                                }
                                k0Var3 = (listV == null || listV.isEmpty()) ? null : c2.u(listV, (k4.V) k2Var.f21087b);
                                if (k0Var3 != null) {
                                    k4.r0 r0Var2 = k0Var3.f19891a;
                                    if (r0Var2 != null) {
                                        k0Var4 = new k4.k0(r0Var2);
                                    } else {
                                        k0Var4 = k0Var3.f19892b;
                                    }
                                }
                                k0Var2 = new k4.k0(Y0.a(map, v12.f20888c, v12.f20886a, v12.f20887b, k0Var4));
                            } catch (RuntimeException e10) {
                                k0Var2 = new k4.k0(k4.r0.f19940g.g("failed to parse service config").f(e10));
                            }
                            k0Var4 = k0Var2;
                        }
                    }
                }
                fVar.f743d = k0Var4;
            }
        } catch (Exception e11) {
            fVar.f741b = k4.r0.f19946n.g("Unable to resolve host " + str).f(e11);
        }
        return fVar;
    }

    public final void v() {
        if (this.f20868q || this.f20864m) {
            return;
        }
        if (this.l) {
            long j4 = this.f20861i;
            if (j4 != 0) {
                if (j4 <= 0) {
                    return;
                }
                TimeUnit timeUnit = TimeUnit.NANOSECONDS;
                if (this.f20863k.b() <= j4) {
                    return;
                }
            }
        }
        this.f20868q = true;
        this.f20865n.execute(new E(this, this.f20869r));
    }

    public final List w() {
        try {
            try {
                S s6 = this.f20855c;
                String str = this.f20858f;
                s6.getClass();
                List listUnmodifiableList = Collections.unmodifiableList(Arrays.asList(InetAddress.getAllByName(str)));
                ArrayList arrayList = new ArrayList(listUnmodifiableList.size());
                Iterator it = listUnmodifiableList.iterator();
                while (it.hasNext()) {
                    arrayList.add(new C2411y(new InetSocketAddress((InetAddress) it.next(), this.f20859g)));
                }
                return Collections.unmodifiableList(arrayList);
            } catch (Exception e6) {
                Object obj = E3.u.f1176a;
                if (e6 instanceof RuntimeException) {
                    throw ((RuntimeException) e6);
                }
                throw new RuntimeException(e6);
            }
        } catch (Throwable th) {
            if (0 != 0) {
                f20847s.log(Level.FINE, "Address resolution failure", (Throwable) null);
            }
            throw th;
        }
    }
}
