package io.netty.handler.traffic;

import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.util.Objects;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import kotlinx.serialization.json.internal.AbstractJsonLexerKt;

/* JADX INFO: loaded from: classes.dex */
public class TrafficCounter {
    private static final InternalLogger logger = InternalLoggerFactory.getInstance((Class<?>) TrafficCounter.class);
    public final ScheduledExecutorService executor;
    private long lastCumulativeTime;
    private volatile long lastReadBytes;
    private long lastReadThroughput;
    private volatile long lastReadingTime;
    private long lastWriteThroughput;
    private volatile long lastWritingTime;
    private volatile long lastWrittenBytes;
    public Runnable monitor;
    public volatile boolean monitorActive;
    public final String name;
    private long readingTime;
    private long realWriteThroughput;
    public volatile ScheduledFuture<?> scheduledFuture;
    public final AbstractTrafficShapingHandler trafficShapingHandler;
    private long writingTime;
    private final AtomicLong currentWrittenBytes = new AtomicLong();
    private final AtomicLong currentReadBytes = new AtomicLong();
    private final AtomicLong cumulativeWrittenBytes = new AtomicLong();
    private final AtomicLong cumulativeReadBytes = new AtomicLong();
    public final AtomicLong lastTime = new AtomicLong();
    private final AtomicLong realWrittenBytes = new AtomicLong();
    public final AtomicLong checkInterval = new AtomicLong(1000);

    public final class TrafficMonitoringTask implements Runnable {
        private TrafficMonitoringTask() {
        }

        @Override // java.lang.Runnable
        public void run() {
            if (TrafficCounter.this.monitorActive) {
                TrafficCounter.this.resetAccounting(TrafficCounter.milliSecondFromNano());
                TrafficCounter trafficCounter = TrafficCounter.this;
                AbstractTrafficShapingHandler abstractTrafficShapingHandler = trafficCounter.trafficShapingHandler;
                if (abstractTrafficShapingHandler != null) {
                    abstractTrafficShapingHandler.doAccounting(trafficCounter);
                }
                TrafficCounter trafficCounter2 = TrafficCounter.this;
                trafficCounter2.scheduledFuture = trafficCounter2.executor.schedule(this, trafficCounter2.checkInterval.get(), TimeUnit.MILLISECONDS);
            }
        }
    }

    public TrafficCounter(AbstractTrafficShapingHandler abstractTrafficShapingHandler, ScheduledExecutorService scheduledExecutorService, String str, long j2) {
        if (abstractTrafficShapingHandler == null) {
            throw new IllegalArgumentException("trafficShapingHandler");
        }
        Objects.requireNonNull(str, "name");
        this.trafficShapingHandler = abstractTrafficShapingHandler;
        this.executor = scheduledExecutorService;
        this.name = str;
        init(j2);
    }

    public TrafficCounter(ScheduledExecutorService scheduledExecutorService, String str, long j2) {
        Objects.requireNonNull(str, "name");
        this.trafficShapingHandler = null;
        this.executor = scheduledExecutorService;
        this.name = str;
        init(j2);
    }

    private void init(long j2) {
        this.lastCumulativeTime = System.currentTimeMillis();
        long jMilliSecondFromNano = milliSecondFromNano();
        this.writingTime = jMilliSecondFromNano;
        this.readingTime = jMilliSecondFromNano;
        this.lastWritingTime = jMilliSecondFromNano;
        this.lastReadingTime = this.writingTime;
        configure(j2);
    }

    public static long milliSecondFromNano() {
        return System.nanoTime() / 1000000;
    }

    public void bytesRealWriteFlowControl(long j2) {
        this.realWrittenBytes.addAndGet(j2);
    }

    public void bytesRecvFlowControl(long j2) {
        this.currentReadBytes.addAndGet(j2);
        this.cumulativeReadBytes.addAndGet(j2);
    }

    public void bytesWriteFlowControl(long j2) {
        this.currentWrittenBytes.addAndGet(j2);
        this.cumulativeWrittenBytes.addAndGet(j2);
    }

    public long checkInterval() {
        return this.checkInterval.get();
    }

    public void configure(long j2) {
        long j3 = (j2 / 10) * 10;
        if (this.checkInterval.getAndSet(j3) != j3) {
            if (j3 > 0) {
                start();
            } else {
                stop();
                this.lastTime.set(milliSecondFromNano());
            }
        }
    }

    public long cumulativeReadBytes() {
        return this.cumulativeReadBytes.get();
    }

    public long cumulativeWrittenBytes() {
        return this.cumulativeWrittenBytes.get();
    }

    public long currentReadBytes() {
        return this.currentReadBytes.get();
    }

    public long currentWrittenBytes() {
        return this.currentWrittenBytes.get();
    }

    public long getRealWriteThroughput() {
        return this.realWriteThroughput;
    }

    public AtomicLong getRealWrittenBytes() {
        return this.realWrittenBytes;
    }

    public long lastCumulativeTime() {
        return this.lastCumulativeTime;
    }

    public long lastReadBytes() {
        return this.lastReadBytes;
    }

    public long lastReadThroughput() {
        return this.lastReadThroughput;
    }

    public long lastTime() {
        return this.lastTime.get();
    }

    public long lastWriteThroughput() {
        return this.lastWriteThroughput;
    }

    public long lastWrittenBytes() {
        return this.lastWrittenBytes;
    }

    public String name() {
        return this.name;
    }

    @Deprecated
    public long readTimeToWait(long j2, long j3, long j4) {
        return readTimeToWait(j2, j3, j4, milliSecondFromNano());
    }

    /* JADX WARN: Removed duplicated region for block: B:18:0x0081 A[PHI: r5
      0x0081: PHI (r5v9 long) = (r5v5 long), (r5v10 long) binds: [B:32:0x00ea, B:17:0x007f] A[DONT_GENERATE, DONT_INLINE]] */
    /* JADX WARN: Removed duplicated region for block: B:19:0x0084 A[PHI: r9 r21
      0x0084: PHI (r9v2 long) = (r9v1 long), (r9v5 long) binds: [B:30:0x00e1, B:15:0x0076] A[DONT_GENERATE, DONT_INLINE]
      0x0084: PHI (r21v4 long) = (r21v2 long), (r21v5 long) binds: [B:30:0x00e1, B:15:0x0076] A[DONT_GENERATE, DONT_INLINE]] */
    /*
        Code decompiled incorrectly, please refer to instructions dump.
        To view partially-correct add '--show-bad-code' argument
    */
    public long readTimeToWait(long r21, long r23, long r25, long r27) {
        /*
            Method dump skipped, instruction units count: 239
            To view this dump add '--comments-level debug' option
        */
        throw new UnsupportedOperationException("Method not decompiled: io.netty.handler.traffic.TrafficCounter.readTimeToWait(long, long, long, long):long");
    }

    public synchronized void resetAccounting(long j2) {
        long andSet = j2 - this.lastTime.getAndSet(j2);
        if (andSet == 0) {
            return;
        }
        InternalLogger internalLogger = logger;
        if (internalLogger.isDebugEnabled() && andSet > (checkInterval() << 1)) {
            internalLogger.debug("Acct schedule not ok: " + andSet + " > 2*" + checkInterval() + " from " + this.name);
        }
        this.lastReadBytes = this.currentReadBytes.getAndSet(0L);
        this.lastWrittenBytes = this.currentWrittenBytes.getAndSet(0L);
        this.lastReadThroughput = (this.lastReadBytes * 1000) / andSet;
        this.lastWriteThroughput = (this.lastWrittenBytes * 1000) / andSet;
        this.realWriteThroughput = (this.realWrittenBytes.getAndSet(0L) * 1000) / andSet;
        this.lastWritingTime = Math.max(this.lastWritingTime, this.writingTime);
        this.lastReadingTime = Math.max(this.lastReadingTime, this.readingTime);
    }

    public void resetCumulativeTime() {
        this.lastCumulativeTime = System.currentTimeMillis();
        this.cumulativeReadBytes.set(0L);
        this.cumulativeWrittenBytes.set(0L);
    }

    public synchronized void start() {
        if (this.monitorActive) {
            return;
        }
        this.lastTime.set(milliSecondFromNano());
        long j2 = this.checkInterval.get();
        if (j2 > 0 && this.executor != null) {
            this.monitorActive = true;
            TrafficMonitoringTask trafficMonitoringTask = new TrafficMonitoringTask();
            this.monitor = trafficMonitoringTask;
            this.scheduledFuture = this.executor.schedule(trafficMonitoringTask, j2, TimeUnit.MILLISECONDS);
        }
    }

    public synchronized void stop() {
        if (this.monitorActive) {
            this.monitorActive = false;
            resetAccounting(milliSecondFromNano());
            AbstractTrafficShapingHandler abstractTrafficShapingHandler = this.trafficShapingHandler;
            if (abstractTrafficShapingHandler != null) {
                abstractTrafficShapingHandler.doAccounting(this);
            }
            if (this.scheduledFuture != null) {
                this.scheduledFuture.cancel(true);
            }
        }
    }

    public String toString() {
        StringBuilder sb = new StringBuilder(165);
        sb.append("Monitor ");
        sb.append(this.name);
        sb.append(" Current Speed Read: ");
        sb.append(this.lastReadThroughput >> 10);
        sb.append(" KB/s, ");
        sb.append("Asked Write: ");
        sb.append(this.lastWriteThroughput >> 10);
        sb.append(" KB/s, ");
        sb.append("Real Write: ");
        sb.append(this.realWriteThroughput >> 10);
        sb.append(" KB/s, ");
        sb.append("Current Read: ");
        sb.append(this.currentReadBytes.get() >> 10);
        sb.append(" KB, ");
        sb.append("Current asked Write: ");
        sb.append(this.currentWrittenBytes.get() >> 10);
        sb.append(" KB, ");
        sb.append("Current real Write: ");
        sb.append(this.realWrittenBytes.get() >> 10);
        sb.append(" KB");
        return sb.toString();
    }

    @Deprecated
    public long writeTimeToWait(long j2, long j3, long j4) {
        return writeTimeToWait(j2, j3, j4, milliSecondFromNano());
    }

    public long writeTimeToWait(long j2, long j3, long j4, long j5) {
        bytesWriteFlowControl(j2);
        if (j2 == 0 || j3 == 0) {
            return 0L;
        }
        long j6 = this.lastTime.get();
        long j7 = this.currentWrittenBytes.get();
        long j8 = this.lastWrittenBytes;
        long j9 = this.writingTime;
        long jMax = Math.max(this.lastWritingTime - j6, 0L);
        long j10 = j5 - j6;
        if (j10 > 10) {
            long j11 = (((1000 * j7) / j3) - j10) + jMax;
            if (j11 > 10) {
                InternalLogger internalLogger = logger;
                if (internalLogger.isDebugEnabled()) {
                    internalLogger.debug("Time: " + j11 + AbstractJsonLexerKt.COLON + j7 + AbstractJsonLexerKt.COLON + j10 + AbstractJsonLexerKt.COLON + jMax);
                }
                if (j11 > j4 && (j5 + j11) - j9 > j4) {
                    j11 = j4;
                }
                this.writingTime = Math.max(j9, j5 + j11);
                return j11;
            }
        } else {
            long j12 = j7 + j8;
            long j13 = this.checkInterval.get() + j10;
            long j14 = (((1000 * j12) / j3) - j13) + jMax;
            if (j14 > 10) {
                InternalLogger internalLogger2 = logger;
                if (internalLogger2.isDebugEnabled()) {
                    internalLogger2.debug("Time: " + j14 + AbstractJsonLexerKt.COLON + j12 + AbstractJsonLexerKt.COLON + j13 + AbstractJsonLexerKt.COLON + jMax);
                }
                if (j14 > j4 && (j5 + j14) - j9 > j4) {
                    j14 = j4;
                }
                this.writingTime = Math.max(j9, j5 + j14);
                return j14;
            }
        }
        this.writingTime = Math.max(j9, j5);
        return 0L;
    }
}
