package com.test.basd.supercleanermax.helps

import android.net.TrafficStats
import android.os.SystemClock
import android.util.Log

object NetWorkSpeed {


    var monitorSwitch = false

    @Volatile
    var preElapsedRealtime: Long = 0

    @Volatile
    var totalRxBytes: Long = 0

    @Volatile
    var totalTxBytes: Long = 0

    @Volatile
    var totalRxSpeed: Long = 0 //下载

    @Volatile
    var totalTxSpeed: Long = 0 //上传


    // 开启网速监控
    fun startMoritor() {
        monitorSwitch = true
        if (preElapsedRealtime == 0L) {
            preElapsedRealtime = SystemClock.elapsedRealtime()
            totalRxBytes = TrafficStats.getTotalRxBytes()
            totalTxBytes = TrafficStats.getTotalTxBytes()
        }
        while (monitorSwitch) {
            try {
                val totalRxBytes = TrafficStats.getTotalRxBytes()
                val totalTxBytes = TrafficStats.getTotalTxBytes()
                // SystemClock.elapsedRealtime() 的计时起点是系统启动时间，即在开机后第一次调用该方法时返回0. 此处使用 SystemClock.elapsedRealtime() 来计算时间间隔
                val elapsedRealtime = SystemClock.elapsedRealtime()
                val j10 = (elapsedRealtime - preElapsedRealtime) / 1000
                val totalTxSpeed = ((totalTxBytes - this.totalTxBytes) / j10)
                val totalRxSpeed = ((totalRxBytes - this.totalRxBytes) / j10)
                this.totalRxBytes = totalRxBytes
                this.totalTxBytes = totalTxBytes
                this.totalTxSpeed = totalTxSpeed
                this.totalRxSpeed = totalRxSpeed
                preElapsedRealtime = elapsedRealtime
                Log.i("networkSpeedMonitor", "Tx: $totalTxSpeed, Rx: $totalRxSpeed")
            } catch (e10: Exception) {
            }
            waitAMoment(4000L)
        }
    }

    // 停止网速监控
    fun stopMonitor() {
        monitorSwitch = false
    }

    fun waitAMoment(j10: Long) {
        try {
            Thread.sleep(j10)
        } catch (e10: InterruptedException) {
        }
    }
}