package okhttp3.internal.connection;

import c.h;
import c.k;
import c.q.d.g;
import c.q.d.j;
import java.io.IOException;
import java.lang.ref.Reference;
import java.net.Proxy;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import okhttp3.Address;
import okhttp3.ConnectionPool;
import okhttp3.Route;
import okhttp3.internal.Util;
import okhttp3.internal.connection.Transmitter;
import okhttp3.internal.platform.Platform;

/* JADX INFO: compiled from: RealConnectionPool.kt */
/* JADX INFO: loaded from: classes.dex */
public final class RealConnectionPool {
    public static final Companion Companion = new Companion(null);
    private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue(), Util.threadFactory("OkHttp ConnectionPool", true));
    private final RealConnectionPool$cleanupRunnable$1 cleanupRunnable;
    private boolean cleanupRunning;
    private final ArrayDeque<RealConnection> connections;
    private final long keepAliveDurationNs;
    private final int maxIdleConnections;
    private final RouteDatabase routeDatabase;

    /* JADX INFO: compiled from: RealConnectionPool.kt */
    public static final class Companion {
        private Companion() {
        }

        public final RealConnectionPool get(ConnectionPool connectionPool) {
            j.c(connectionPool, "connectionPool");
            return connectionPool.getDelegate$okhttp();
        }

        public /* synthetic */ Companion(g gVar) {
            this();
        }
    }

    /* JADX WARN: Type inference failed for: r3v1, types: [okhttp3.internal.connection.RealConnectionPool$cleanupRunnable$1] */
    public RealConnectionPool(int i, long j, TimeUnit timeUnit) {
        j.c(timeUnit, "timeUnit");
        this.maxIdleConnections = i;
        this.keepAliveDurationNs = timeUnit.toNanos(j);
        this.cleanupRunnable = new Runnable() { // from class: okhttp3.internal.connection.RealConnectionPool$cleanupRunnable$1
            @Override // java.lang.Runnable
            public void run() {
                while (true) {
                    long jCleanup = this.this$0.cleanup(System.nanoTime());
                    if (jCleanup == -1) {
                        return;
                    } else {
                        try {
                            Util.lockAndWaitNanos(this.this$0, jCleanup);
                        } catch (InterruptedException unused) {
                        }
                    }
                }
            }
        };
        this.connections = new ArrayDeque<>();
        this.routeDatabase = new RouteDatabase();
        if (j > 0) {
            return;
        }
        throw new IllegalArgumentException(("keepAliveDuration <= 0: " + j).toString());
    }

    private final int pruneAndGetAllocationCount(RealConnection realConnection, long j) {
        List<Reference<Transmitter>> transmitters = realConnection.getTransmitters();
        int i = 0;
        while (i < transmitters.size()) {
            Reference<Transmitter> reference = transmitters.get(i);
            if (reference.get() != null) {
                i++;
            } else {
                if (reference == null) {
                    throw new h("null cannot be cast to non-null type okhttp3.internal.connection.Transmitter.TransmitterReference");
                }
                Platform.Companion.get().logCloseableLeak("A connection to " + realConnection.route().address().url() + " was leaked. Did you forget to close a response body?", ((Transmitter.TransmitterReference) reference).getCallStackTrace());
                transmitters.remove(i);
                realConnection.setNoNewExchanges(true);
                if (transmitters.isEmpty()) {
                    realConnection.setIdleAtNanos$okhttp(j - this.keepAliveDurationNs);
                    return 0;
                }
            }
        }
        return transmitters.size();
    }

    public final long cleanup(long j) {
        synchronized (this) {
            long j2 = Long.MIN_VALUE;
            RealConnection realConnection = null;
            int i = 0;
            int i2 = 0;
            for (RealConnection realConnection2 : this.connections) {
                j.b(realConnection2, "connection");
                if (pruneAndGetAllocationCount(realConnection2, j) > 0) {
                    i2++;
                } else {
                    i++;
                    long idleAtNanos$okhttp = j - realConnection2.getIdleAtNanos$okhttp();
                    if (idleAtNanos$okhttp > j2) {
                        realConnection = realConnection2;
                        j2 = idleAtNanos$okhttp;
                    }
                }
            }
            if (j2 < this.keepAliveDurationNs && i <= this.maxIdleConnections) {
                if (i > 0) {
                    return this.keepAliveDurationNs - j2;
                }
                if (i2 > 0) {
                    return this.keepAliveDurationNs;
                }
                this.cleanupRunning = false;
                return -1L;
            }
            this.connections.remove(realConnection);
            if (realConnection != null) {
                Util.closeQuietly(realConnection.socket());
                return 0L;
            }
            j.g();
            throw null;
        }
    }

    public final void connectFailed(Route route, IOException iOException) {
        j.c(route, "failedRoute");
        j.c(iOException, "failure");
        if (route.proxy().type() != Proxy.Type.DIRECT) {
            Address address = route.address();
            address.proxySelector().connectFailed(address.url().uri(), route.proxy().address(), iOException);
        }
        this.routeDatabase.failed(route);
    }

    public final boolean connectionBecameIdle(RealConnection realConnection) {
        j.c(realConnection, "connection");
        boolean zHoldsLock = Thread.holdsLock(this);
        if (k.f1418a && !zHoldsLock) {
            throw new AssertionError("Assertion failed");
        }
        if (realConnection.getNoNewExchanges() || this.maxIdleConnections == 0) {
            this.connections.remove(realConnection);
            return true;
        }
        notifyAll();
        return false;
    }

    public final synchronized int connectionCount() {
        return this.connections.size();
    }

    public final void evictAll() {
        ArrayList arrayList = new ArrayList();
        synchronized (this) {
            Iterator<RealConnection> it = this.connections.iterator();
            j.b(it, "connections.iterator()");
            while (it.hasNext()) {
                RealConnection next = it.next();
                if (next.getTransmitters().isEmpty()) {
                    next.setNoNewExchanges(true);
                    j.b(next, "connection");
                    arrayList.add(next);
                    it.remove();
                }
            }
            c.j jVar = c.j.f1417a;
        }
        Iterator it2 = arrayList.iterator();
        while (it2.hasNext()) {
            Util.closeQuietly(((RealConnection) it2.next()).socket());
        }
    }

    public final boolean getCleanupRunning() {
        return this.cleanupRunning;
    }

    public final RouteDatabase getRouteDatabase() {
        return this.routeDatabase;
    }

    public final synchronized int idleConnectionCount() {
        int i;
        ArrayDeque<RealConnection> arrayDeque = this.connections;
        i = 0;
        if (!(arrayDeque instanceof Collection) || !arrayDeque.isEmpty()) {
            Iterator<T> it = arrayDeque.iterator();
            while (it.hasNext()) {
                if (((RealConnection) it.next()).getTransmitters().isEmpty() && (i = i + 1) < 0) {
                    c.l.h.k();
                    throw null;
                }
            }
        }
        return i;
    }

    public final void put(RealConnection realConnection) {
        j.c(realConnection, "connection");
        boolean zHoldsLock = Thread.holdsLock(this);
        if (k.f1418a && !zHoldsLock) {
            throw new AssertionError("Assertion failed");
        }
        if (!this.cleanupRunning) {
            this.cleanupRunning = true;
            executor.execute(this.cleanupRunnable);
        }
        this.connections.add(realConnection);
    }

    public final void setCleanupRunning(boolean z) {
        this.cleanupRunning = z;
    }

    public final boolean transmitterAcquirePooledConnection(Address address, Transmitter transmitter, List<Route> list, boolean z) {
        j.c(address, "address");
        j.c(transmitter, "transmitter");
        boolean zHoldsLock = Thread.holdsLock(this);
        if (k.f1418a && !zHoldsLock) {
            throw new AssertionError("Assertion failed");
        }
        for (RealConnection realConnection : this.connections) {
            if (!z || realConnection.isMultiplexed()) {
                if (realConnection.isEligible$okhttp(address, list)) {
                    j.b(realConnection, "connection");
                    transmitter.acquireConnectionNoEvents(realConnection);
                    return true;
                }
            }
        }
        return false;
    }
}
