package com.ez.ertc.meeting.widget;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.ez.basertc.RTCConstant;
import com.ez.dclog.statistics.ERTCLocalAudioStats;
import com.ez.dclog.statistics.ERTCLocalVideoStats;
import com.ez.dclog.statistics.ERTCRemoteAudioStats;
import com.ez.dclog.statistics.ERTCRemoteVideoStats;
import com.ez.ertc.meeting.R;
import com.ez.ertc.meeting.R2;
import com.ez.ertc.meeting.constant.SharingType;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author xiezuoyuan
 * @time 2018/11/21 19:28
 */
public class ErtcMonitorDialog extends Dialog {
    //    共享屏幕
    @BindView(R2.id.llMonitorShare)
    LinearLayout llMonitorShare;
    @BindView(R2.id.tvRemotevideoUsername)
    TextView tvRemotevideoUsername;
    @BindView(R2.id.tvRemotevideoReceivedBitrate)
    TextView tvRemotevideoReceivedBitrate;
    @BindView(R2.id.tvRemotevideoPacketLossRate)
    TextView tvRemotevideoPacketLossRate;
    @BindView(R2.id.tvRemotevideoTotalFrozenTime)
    TextView tvRemotevideoTotalFrozenTime;
    @BindView(R2.id.tvRemotevideoFrozenRate)
    TextView tvRemotevideoFrozenRate;
    @BindView(R2.id.tvRemotevideoPacketCount)
    TextView tvRemotevideoPacketCount;
    @BindView(R2.id.tvRemotevideoUncompensateLoss)
    TextView tvRemotevideoUncompensateLoss;
    @BindView(R2.id.tvRemotevideoReceivedFrameRate)
    TextView tvRemotevideoReceivedFrameRate;
    @BindView(R2.id.tvRemotevideoWH)
    TextView tvRemotevideoWH;

    //    发送音频
    @BindView(R2.id.tvSentBitrate)
    TextView tvSentBitrate;
    @BindView(R2.id.tvAudioPacketCount)
    TextView tvAudioPacketCount;
    @BindView(R2.id.tvAudioPacketLossRate)
    TextView tvAudioPacketLossRate;
    //    发送视频 - 大码流
    @BindView(R2.id.tbVideoBig)
    TableRow tbVideoBig;
    @BindView(R2.id.tvVideoSentBitrateBig)
    TextView tvVideoSentBitrateBig;
    @BindView(R2.id.tvVideoPacketLossRateBig)
    TextView tvVideoPacketLossRateBig;
    @BindView(R2.id.tvVideoPacketCountBig)
    TextView tvVideoPacketCountBig;
    @BindView(R2.id.tvAudioCompensateLossRateBig)
    TextView tvAudioCompensateLossRateBig;
    @BindView(R2.id.tvVideoSentFrameRateBig)
    TextView tvVideoSentFrameRateBig;
    @BindView(R2.id.tvVideoWHBig)
    TextView tvVideoWHBig;
    //    发送视频 - 小码流
    @BindView(R2.id.tbVideoSmall)
    TableRow tbVideoSmall;
    @BindView(R2.id.tvVideoSentBitrateSmall)
    TextView tvVideoSentBitrateSmall;
    @BindView(R2.id.tvVideoPacketLossRateSmall)
    TextView tvVideoPacketLossRateSmall;
    @BindView(R2.id.tvVideoPacketCountSmall)
    TextView tvVideoPacketCountSmall;
    @BindView(R2.id.tvAudioCompensateLossRateSmall)
    TextView tvAudioCompensateLossRateSmall;
    @BindView(R2.id.tvVideoSentFrameRateSmall)
    TextView tvVideoSentFrameRateSmall;
    @BindView(R2.id.tvVideoWHSmall)
    TextView tvVideoWHSmall;
    //    发送视频 - 屏幕共享
    @BindView(R2.id.tbVideoShare)
    TableRow tbVideoShare;
    @BindView(R2.id.tvVideoSentBitrateShare)
    TextView tvVideoSentBitrateShare;
    @BindView(R2.id.tvVideoPacketLossRateShare)
    TextView tvVideoPacketLossRateShare;
    @BindView(R2.id.tvVideoPacketCountShare)
    TextView tvVideoPacketCountShare;
    @BindView(R2.id.tvAudioCompensateLossRateShare)
    TextView tvAudioCompensateLossRateShare;
    @BindView(R2.id.tvVideoSentFrameRateShare)
    TextView tvVideoSentFrameRateShare;
    @BindView(R2.id.tvVideoWHShare)
    TextView tvVideoWHShare;

    //    接收音频
    @BindView(R2.id.tlReceiveAudio)
    TableLayout tlReceiveAudio;

    //    接收视频
    @BindView(R2.id.tlReceiveVideo)
    TableLayout tlReceiveVideo;

    private LayoutInflater mLayoutInflater;
    private SharingType sharingType;

    private Map<String, ERTCRemoteVideoStats> remoteVideoStatsMap = new HashMap<>();
    private Map<String, ERTCRemoteAudioStats> remoteAudioStatsMap = new HashMap<>();

    public ErtcMonitorDialog(@NonNull Context context) {
        super(context, R.style.ezmCommonDialog);
        getWindow().getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        getWindow().setAttributes(lp);
        setCanceledOnTouchOutside(true);
        mLayoutInflater = LayoutInflater.from(context);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ertc_dialog_monitor);
        ButterKnife.bind(this);
        findViewById(R.id.tvClose).setOnClickListener(v -> {
            dismiss();
        });
    }

    public void setLocalAudioStats(ERTCLocalAudioStats localAudioStats) {
        tvSentBitrate.setText(localAudioStats != null ? localAudioStats.sentBitrate+"" : "-");
        tvAudioPacketCount.setText(localAudioStats != null ? localAudioStats.packetCount+"" : "-");
        tvAudioPacketLossRate.setText(localAudioStats != null ? localAudioStats.packetLossRate+"%" : "-");
    }

    public void setLocalVideoStats(ERTCLocalVideoStats localVideoStats) {
        ERTCLocalVideoStats.VideoStat videoStat = localVideoStats != null ? localVideoStats.videoList.get(0) : null;
        tbVideoBig.setVisibility(localVideoStats != null ? View.VISIBLE : View.GONE);
        tbVideoSmall.setVisibility(localVideoStats != null ? View.VISIBLE : View.GONE);
        if(videoStat != null && videoStat.streamType == RTCConstant.ERTC_VIDEO_STREAM_TYPE_BIG) {
            tvVideoSentBitrateBig.setText(localVideoStats != null ? videoStat.sentBitrate + "" : "-");
            tvVideoPacketLossRateBig.setText(localVideoStats != null ? localVideoStats.packetLossRate + "%" : "-");
            tvVideoPacketCountBig.setText(localVideoStats != null ? videoStat.packetCount + "" : "-");
            tvAudioCompensateLossRateBig.setText(localVideoStats != null ? videoStat.compensateLossRate + "%" : "-");
            tvVideoSentFrameRateBig.setText(localVideoStats != null ? videoStat.sentFrameRate + "" : "-");
            tvVideoWHBig.setText(localVideoStats != null ? videoStat.width + "*" + videoStat.height : "-");
        }
        if(videoStat != null && videoStat.streamType == RTCConstant.ERTC_VIDEO_STREAM_TYPE_SMALL) {
            tvVideoSentBitrateSmall.setText(localVideoStats != null ? videoStat.sentBitrate + "" : "-");
            tvVideoPacketLossRateSmall.setText(localVideoStats != null ? localVideoStats.packetLossRate + "%" : "-");
            tvVideoPacketCountSmall.setText(localVideoStats != null ? videoStat.packetCount + "" : "-");
            tvAudioCompensateLossRateSmall.setText(localVideoStats != null ? videoStat.compensateLossRate + "%" : "-");
            tvVideoSentFrameRateSmall.setText(localVideoStats != null ? videoStat.sentFrameRate + "" : "-");
            tvVideoWHSmall.setText(localVideoStats != null ? videoStat.width + "*" + videoStat.height : "-");
        }
    }

    public void setShareVideoStats(ERTCLocalVideoStats localVideoStats) {
        ERTCLocalVideoStats.VideoStat videoStat = localVideoStats != null ? localVideoStats.videoList.get(0) : null;
        tbVideoShare.setVisibility(localVideoStats != null ? View.VISIBLE : View.GONE);
        if(videoStat != null && videoStat.streamType == RTCConstant.ERTC_VIDEO_STREAM_TYPE_SHARE) {
            tvVideoSentBitrateShare.setText(localVideoStats != null ? videoStat.sentBitrate + "" : "-");
            tvVideoPacketLossRateShare.setText(localVideoStats != null ? localVideoStats.packetLossRate + "%" : "-");
            tvVideoPacketCountShare.setText(localVideoStats != null ? videoStat.packetCount + "" : "-");
            tvAudioCompensateLossRateShare.setText(localVideoStats != null ? videoStat.compensateLossRate + "%" : "-");
            tvVideoSentFrameRateShare.setText(localVideoStats != null ? videoStat.sentFrameRate + "" : "-");
            tvVideoWHShare.setText(localVideoStats != null ? videoStat.width + "*" + videoStat.height : "-");
        }
    }

    public void addRemoteAudioStats(ERTCRemoteAudioStats remoteAudioStats) {
        remoteAudioStatsMap.put(remoteAudioStats.userId, remoteAudioStats);
        updateRemoteAudioStatsView();
    }
    public void removeRemoteAudioStats(String userId) {
        if(remoteAudioStatsMap.containsKey(userId)) {
            remoteAudioStatsMap.remove(userId);
            updateRemoteAudioStatsView();
        }
    }
    private void updateRemoteAudioStatsView(){
        tlReceiveAudio.removeAllViews();
        for (ERTCRemoteAudioStats audioStats : remoteAudioStatsMap.values()) {
            TableRow audioStatsView = (TableRow) mLayoutInflater.inflate(R.layout.ertc_dialog_monitor_remoteaudio_item, null, false);
            ((TextView)audioStatsView.findViewById(R.id.tvRemoteaudioUsername)).setText(audioStats.userId);
            ((TextView)audioStatsView.findViewById(R.id.tvRemoteaudioReceivedBitrate)).setText(String.valueOf(audioStats.receivedBitrate));
            ((TextView)audioStatsView.findViewById(R.id.tvRemoteaudioPacketLossRate)).setText(String.valueOf(audioStats.packetLossRate));
            ((TextView)audioStatsView.findViewById(R.id.tvRemoteaudioTotalFrozenTime)).setText(String.valueOf(audioStats.totalFrozenTime));
            ((TextView)audioStatsView.findViewById(R.id.tvRemoteaudioFrozenRate)).setText(String.valueOf(audioStats.frozenRate));
            ((TextView)audioStatsView.findViewById(R.id.tvRemoteaudioPacketCount)).setText(String.valueOf(audioStats.packetCount));
            ((TextView)audioStatsView.findViewById(R.id.tvRemoteaudioPlcPacketCount)).setText(String.valueOf(audioStats.plcPacketCount));
            ((TextView)audioStatsView.findViewById(R.id.tvRemoteaudioUncompensateLoss)).setText(String.valueOf(audioStats.uncompensateLoss));
            ((TextView)audioStatsView.findViewById(R.id.tvRemoteaudioTotalTime)).setText(String.valueOf(audioStats.totalTime));
            tlReceiveAudio.addView(audioStatsView);
        }
    }

    public void addRemoteVideoStats(ERTCRemoteVideoStats remoteVideoStats) {
        remoteVideoStatsMap.put(remoteVideoStats.userId, remoteVideoStats);
        updateRemoteVideoStatsView();
    }
    public void removeRemoteVideoStats(String userId) {
        if(remoteVideoStatsMap.containsKey(userId)) {
            remoteVideoStatsMap.remove(userId);
            updateRemoteVideoStatsView();
        }
    }
    private void updateRemoteVideoStatsView(){
        tlReceiveVideo.removeAllViews();
        for (ERTCRemoteVideoStats videoStats : remoteVideoStatsMap.values()) {
            TableRow videoStatsView = (TableRow) mLayoutInflater.inflate(R.layout.ertc_dialog_monitor_remotevideo_item, null, false);
            ((TextView)videoStatsView.findViewById(R.id.tvRemotevideoUsername)).setText(videoStats.userId);
            ((TextView)videoStatsView.findViewById(R.id.tvRemotevideoReceivedBitrate)).setText(String.valueOf(videoStats.receivedBitrate));
            ((TextView)videoStatsView.findViewById(R.id.tvRemotevideoPacketLossRate)).setText(String.valueOf(videoStats.packetLossRate));
            ((TextView)videoStatsView.findViewById(R.id.tvRemotevideoTotalFrozenTime)).setText(String.valueOf(videoStats.totalFrozenTime));
            ((TextView)videoStatsView.findViewById(R.id.tvRemotevideoFrozenRate)).setText(String.valueOf(videoStats.frozenRate));
            ((TextView)videoStatsView.findViewById(R.id.tvRemotevideoPacketCount)).setText(String.valueOf(videoStats.packetCount));
            ((TextView)videoStatsView.findViewById(R.id.tvRemotevideoUncompensateLoss)).setText(String.valueOf(videoStats.uncompensateLoss));
            ((TextView)videoStatsView.findViewById(R.id.tvRemotevideoReceivedFrameRate)).setText(String.valueOf(videoStats.receivedFrameRate));
            ((TextView)videoStatsView.findViewById(R.id.tvRemotevideoStreamType)).setText(String.valueOf(videoStats.streamType));
            ((TextView)videoStatsView.findViewById(R.id.tvRemotevideoWH)).setText(videoStats.width+"*"+videoStats.height);
            tlReceiveVideo.addView(videoStatsView);
        }
    }

    public void setShareVideoStats(ERTCRemoteVideoStats videoStats) {
        tvRemotevideoUsername.setText(videoStats != null ? videoStats.userId : "--");
        tvRemotevideoReceivedBitrate.setText(videoStats != null ? String.valueOf(videoStats.receivedBitrate) : "--");
        tvRemotevideoPacketLossRate.setText(videoStats != null ? String.valueOf(videoStats.packetLossRate) : "--");
        tvRemotevideoTotalFrozenTime.setText(videoStats != null ? String.valueOf(videoStats.totalFrozenTime) : "--");
        tvRemotevideoFrozenRate.setText(videoStats != null ? String.valueOf(videoStats.frozenRate) : "--");
        tvRemotevideoPacketCount.setText(videoStats != null ? String.valueOf(videoStats.packetCount) : "--");
        tvRemotevideoUncompensateLoss.setText(videoStats != null ? String.valueOf(videoStats.uncompensateLoss) : "--");
        tvRemotevideoReceivedFrameRate.setText(videoStats != null ? String.valueOf(videoStats.receivedFrameRate) : "--");
        tvRemotevideoWH.setText(videoStats != null ? videoStats.width+"*"+videoStats.height : "--");
    }

    /**
     * 需要onShow更新
     * @param sharingType
     * @param isCreator
     */
    public void onSharingTypeChanged(SharingType sharingType , boolean isCreator){
        this.sharingType = sharingType;
        //共享相关先隐藏
//        tvCost.setText("--");
//        tvFps.setText("--");
//        tvResolution.setText("--");
        tvRemotevideoUsername.setText("--");
        tvRemotevideoReceivedBitrate.setText("--");
        tvRemotevideoPacketLossRate.setText("--");
        tvRemotevideoTotalFrozenTime.setText("--");
        tvRemotevideoFrozenRate.setText("--");
        tvRemotevideoPacketCount.setText("--");
        tvRemotevideoUncompensateLoss.setText("--");
        tvRemotevideoReceivedFrameRate.setText("--");
        tvRemotevideoWH.setText("--");
        if ((sharingType == SharingType.ST_Desktop || sharingType == SharingType.ST_Desktop_Picture) & !isCreator){
//            tvTarget.setText(isCreator ? R.string.ys_mt_room_dialog_monitor_target_send : R.string.ys_mt_room_dialog_monitor_target_receive);
//            if (sharingType == Models.SharingType.ST_Desktop){
//                tvMode.setText(R.string.ys_mt_room_dialog_monitor_mode_video);
//            } else {
//                tvMode.setText(R.string.ys_mt_room_dialog_monitor_mode_picture);
//            }
            llMonitorShare.setVisibility(View.VISIBLE);
        } else {
            llMonitorShare.setVisibility(View.GONE);
        }
    }

    public void onSharePicCost(long time,int width, int height){
        if (llMonitorShare.getVisibility() == View.VISIBLE && sharingType == SharingType.ST_Desktop_Picture){
//            tvCost.setText(time+"");
//            tvResolution.setText(width + "*" + height);
        }
    }

    public void onScreenEnStatus(double fps, int bitrate, int width, int height) {
        if (sharingType != SharingType.ST_Desktop){
            return;
        }
//        tvFps.setText(Math.round(fps)+"");
//        tvResolution.setText(width + "*" + height);
    }

}
