package com.ez.ertc.meeting.ui;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ez.basertc.RTCConstant;
import com.ez.basertc.RTCSpeedTestListener;
import com.ez.baselib.utils.LogUtil;
import com.ez.ertc.meeting.ErtcEzmHelper;
import com.ez.ertc.meeting.R;
import com.ez.ertc.meeting.R2;
import com.ez.ertc.meeting.base.YsBaseActivity;
import com.ez.ertc.meeting.utils.ErrorDealer;
import com.ez.ertcengine.ERTCEngine;

import org.jetbrains.annotations.NotNull;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 *
 *
 * @author xiezuoyuan
 * @time 2021/11/4 19:53
 */
public class ErtcTestingActivity extends YsBaseActivity {
    private static final String KEY_UP_SPEED = "KEY_UP_SPEED";
    private static final String KEY_DOWN_SPEED = "KEY_DOWN_SPEED";
    private static final String KEY_DURATION = "KEY_DURATION";
    public static void start(Context context,int upSpeed,int downSpeed,int duration) {
        Intent starter = new Intent(context, ErtcTestingActivity.class);
        starter.putExtra(KEY_UP_SPEED,upSpeed);
        starter.putExtra(KEY_DOWN_SPEED,downSpeed);
        starter.putExtra(KEY_DURATION,duration);
        context.startActivity(starter);
    }
    @BindView(R2.id.viewResult)
    View viewResult;
    @BindView(R2.id.viewTesting)
    View viewTesting;
    @BindView(R2.id.tvCost)
    TextView tvCost;//测试执行时间
    @BindView(R2.id.tvNetwork)
    TextView tvNetwork;//互联网连接情况
    @BindView(R2.id.tvServer)
    TextView tvServer;//信令服务器连接情况
    @BindView(R2.id.tvStream)
    TextView tvStream;//流媒体服务器连接情况
    @BindView(R2.id.tvCtocDelay)
    TextView tvCtocDelay;//端到端环回延迟
    @BindView(R2.id.tvUpSpeed)
    TextView tvUpSpeed;//上行带宽
//    @BindView(R2.id.tvUpOut)
//    TextView tvUpOut;//上行 网络状况
//    @BindView(R2.id.tvUpTran)
//    TextView tvUpTran;//上行 客户端成功发包数-服务端接收到的包数
//    @BindView(R2.id.tvUpReceive)
//    TextView tvUpReceive;//上行 服务端接收到的包错序数
//    @BindView(R2.id.tvUpLost)
//    TextView tvUpLost;//上行 丢包数
    @BindView(R2.id.tvUpKbps)
    TextView tvUpKbps;//上行 带宽kbps
    @BindView(R2.id.tvUpLostPercent)
    TextView tvUpLostPercent;//上行 丢包率
//    @BindView(R2.id.tvUpDelay)
//    TextView tvUpDelay;//上行 延迟
    @BindView(R2.id.tvDownSpeed)
    TextView tvDownSpeed;//下行带宽
//    @BindView(R2.id.tvDownOut)
//    TextView tvDownOut;//下行 网络状况
//    @BindView(R2.id.tvDownTran)
//    TextView tvDownTran;//下行 客户端成功发包数-服务端接收到的包数
//    @BindView(R2.id.tvDownReceive)
//    TextView tvDownReceive;//下行 服务端接收到的包错序数
//    @BindView(R2.id.tvDownLost)
//    TextView tvDownLost;//下行 丢包数
    @BindView(R2.id.tvDownKbps)
    TextView tvDownKbps;//下行 带宽kbps
    @BindView(R2.id.tvDownLostPercent)
    TextView tvDownLostPercent;//下行 丢包率
//    @BindView(R2.id.tvDownDelay)
//    TextView tvDownDelay;//下行 延迟
    @BindView(R2.id.llUp)
    View llUp;
    @BindView(R2.id.llDown)
    View llDown;
    @BindView(R2.id.llStream)
    View llStream;
    private int upSpeed,downSpeed,duration;

    @Override
    protected int provideLayoutId() {
        return R.layout.ertc_activity_testing;
    }

    @SuppressLint("NewApi")
    @Override
    protected void initView() {
        ButterKnife.bind(this);
        ImageView pbLoading = findViewById(R.id.pbLoading);
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(pbLoading,"rotation",0f,359f);
        objectAnimator.setDuration(4000);
        objectAnimator.setRepeatCount(-1);
        objectAnimator.setInterpolator(null);
        objectAnimator.start();
    }

    @Override
    protected void initData() {
        upSpeed = getIntent().getIntExtra(KEY_UP_SPEED,0);
        downSpeed = getIntent().getIntExtra(KEY_DOWN_SPEED,0);
        duration = getIntent().getIntExtra(KEY_DURATION,10);
        if (upSpeed == 0){
            llUp.setVisibility(View.GONE);
        }
        if (downSpeed == 0){
            llDown.setVisibility(View.GONE);
        }
        if(ErtcEzmHelper.ertcEngine == null) {
            ertcInit();
        } else {
            setSpeedTestListener();
            ErtcEzmHelper.ertcEngine.startSpeedTest(upSpeed, downSpeed, duration * 1000);
        }
    }

    private void ertcInit() {
        ErtcEzmHelper.getInstance().ertcEnterInitDebug(this)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ERTCEngine>() {
                    @Override
                    public void onSubscribe(@NotNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NotNull ERTCEngine engine) {
                        setSpeedTestListener();
                        ErtcEzmHelper.ertcEngine.startSpeedTest(upSpeed, downSpeed, duration * 1000);
                    }

                    @Override
                    public void onError(@NotNull Throwable e) {
                        ErrorDealer.toastError(e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void setSpeedTestListener() {
        ErtcEzmHelper.ertcEngine.setSpeedTestListener(new RTCSpeedTestListener() {
            @Override
            public void onSpeedTestResult(final RTCConstant.SpeedTestResult result) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LogUtil.d("EZRTCImpl", "onSpeedTestResult success:" + result.success);
                        if(result.success) {
                            viewTesting.setVisibility(View.GONE);
                            viewResult.setVisibility(View.VISIBLE);
                            updateUIData(result);
                        } else {
                            showToast(getResources().getString(R.string.ys_mt_test_result_notok));
                        }
                        ErtcEzmHelper.ertcEngine.stopSpeedTest();
                    }
                });
            }

            @Override
            public void onError(int errorCode) {
                LogUtil.d("EZRTCImpl", "onSpeedTestResult errorCode:" + errorCode);
                showToast(getResources().getString(R.string.ys_mt_test_result_notok));
            }
        });
    }

    private void updateUIData(RTCConstant.SpeedTestResult result) {
        tvCost.setText(duration+"");
        setSpeedLevel(result.quality, tvNetwork);
        if(result.stsConnect == 1){
            tvServer.setText(R.string.ys_mt_test_result_ok);
        } else {
            tvServer.setText(R.string.ys_mt_test_result_notok);
        }
        tvCtocDelay.setText(result.rtt+"");
        tvStream.setText(R.string.ys_mt_test_result_ok);
        if (upSpeed != 0){
            tvUpSpeed.setText(getResources().getString(R.string.ys_mt_test_result_up_rate_format,upSpeed/1024+""));
//            tvUpTran.setText(upProbeInfo.recv+"");//服务端接收包数
//            tvUpReceive.setText(upProbeInfo.miss+"");//服务端接收到的包错序数
//            tvUpLost.setText(upProbeInfo.lost+"");//丢包数
            tvUpKbps.setText(String.format("%.2f",1.0*result.availableUpBandwidth/1024)); //平均码率
            tvUpLostPercent.setText(result.upLostRate + "%");
        }
        if (downSpeed != 0){
            tvDownSpeed.setText(getResources().getString(R.string.ys_mt_test_result_down_rate_format,downSpeed/1024+""));
//            tvDownTran.setText(downProbeInfo.recv+"");
//            tvDownReceive.setText(downProbeInfo.miss+"");
//            tvDownLost.setText(downProbeInfo.lost+"");
            tvDownKbps.setText(String.format("%.2f",1.0*result.availableDownBandwidth/1024));
            tvDownLostPercent.setText(result.downLostRate + "%");
        }
    }

    private void setSpeedLevel(int quality, TextView textView) {
        switch (quality) {
            //良好
            case 1: //当前网络非常好
            case 2: //当前网络比较好
                textView.setText(R.string.ys_mt_test_result_out_good);
                textView.setTextColor(getResources().getColor(R.color.ezm_green));
                break;
            //不佳
            case 3: //当前网络一般
                textView.setText(R.string.ys_mt_test_result_out_poor);
                textView.setTextColor(getResources().getColor(R.color.ezm_red));
                break;
            //较差
            case 4: //当前网络较差
                textView.setText(R.string.ys_mt_test_result_out_bad);
                textView.setTextColor(getResources().getColor(R.color.ezm_red));
                break;
            //极差
            case 5: //当前网络很差
                textView.setText(R.string.ys_mt_test_result_out_terrible);
                textView.setTextColor(getResources().getColor(R.color.ezm_red));
                break;
            //异常
            case 6: //当前网络不满足 ERTC 的最低要求
            case 7: //暂时无法检测到网络质量
            case 8: //网络质量检测已开始还没有完成
            case 0: //网络类型——未定义
                textView.setText(R.string.ys_mt_test_result_notok);
                textView.setTextColor(getResources().getColor(R.color.ezm_red));
                break;
        }
    }

    @OnClick(R2.id.btnRetry)
    public void onClick(){
        onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        LogUtil.d("EZRTCImpl", "stopSpeedTest");
        ErtcEzmHelper.ertcEngine.setSpeedTestListener(null);
        ErtcEzmHelper.ertcEngine.stopSpeedTest();
        super.onBackPressed();
    }
}
