package com.ez.ertc.speedtest

import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
import com.ez.baselib.utils.LogUtil
import com.ez.basertc.RTCConstant
import com.ez.basertc.RTCSpeedTestListener
import com.ez.ertc.MyApp
import com.ez.ertc.R
import com.ez.ertc.base.BaseActivity
import kotlinx.android.synthetic.main.activity_speed_test.*
import java.time.LocalDateTime

class SpeedTestActivity : BaseActivity() {
    private var testInterval = 3 * 1000

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_speed_test)

        MyApp.ertcEngine?.setSpeedTestListener(object : RTCSpeedTestListener {
            override fun onSpeedTestResult(result: RTCConstant.SpeedTestResult?) {
                runOnUiThread {
                    tv_time.text = LocalDateTime.now().toString()
                    tv_quality.text = result?.quality.toString()
                    tv_upLostRate.text = result?.upLostRate.toString()
                    tv_downLostRate.text = result?.downLostRate.toString()
                    tv_rtt.text = result?.rtt.toString()
                    tv_availableUpBandwidth.text = result?.availableUpBandwidth.toString()
                    tv_availableDownBandwidth.text = result?.availableDownBandwidth.toString()
                    tv_stsConnect.text = if(result?.stsConnect == 0) "连接失败" else "连接成功"
                }
            }

            override fun onError(errorCode: Int) {
                LogUtil.d(
                    "EZRTCImpl",
                    "onSpeedTestResult errorCode:$errorCode"
                )
            }
        })

        btn_test_start.setOnClickListener {
            var upBandwidth = Integer.valueOf(edt_upBandwidth.text.toString())
            var downBandwidth = Integer.valueOf(edt_downBandwidth.text.toString())
            var interval = Integer.valueOf(edt_testInterval.text.toString())
            if(interval>0) {
                testInterval = interval * 1000
            }
            if(upBandwidth < 10 || upBandwidth > 50000) {
                toast("预期的上行带宽（kbps，取值范围： 10 ～ 5000，为 0 时不测试）")
                return@setOnClickListener
            }
            if(downBandwidth < 10 || downBandwidth > 50000) {
                toast("预期的下行带宽（kbps，取值范围： 10 ～ 5000，为 0 时不测试）")
                return@setOnClickListener
            }
            MyApp.ertcEngine?.startSpeedTest(upBandwidth, downBandwidth, testInterval)
        }
        btn_test_stop.setOnClickListener {
            MyApp.ertcEngine?.stopSpeedTest()
        }

    }

}