package com.huawei.rtcdemo.activities;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.huawei.rtc.RtcEngine;
import com.huawei.rtc.models.LocalAudioStats;
import com.huawei.rtc.models.LocalVideoStats;
import com.huawei.rtc.models.RemoteAudioStats;
import com.huawei.rtc.models.RemoteVideoStats;
import com.huawei.rtc.models.RemoteViewType;
import com.huawei.rtc.models.StatsInfo;
import com.huawei.rtc.models.UserInfo;
import com.huawei.rtc.utils.RtcConstants;
import com.huawei.rtc.utils.RtcEnums;
import com.huawei.rtcdemo.Constants;
import com.huawei.rtcdemo.R;
import com.huawei.rtcdemo.RtcApplication;
import com.huawei.rtcdemo.adapter.RoomMembersAdapter;
import com.huawei.rtcdemo.bean.BeanRoomMember;
import com.huawei.rtcdemo.ui.UploadDialog;
import com.huawei.rtcdemo.ui.WndArrangeMaker;
import com.huawei.rtcdemo.utils.PrefManager;
import com.huawei.rtcdemo.utils.SreenPropertyUtil;
import com.zyyoona7.lib.EasyPopup;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import static com.huawei.rtc.models.UserInfo.RoleType.ROLE_TYPE_JOINER;
import static com.huawei.rtc.models.UserInfo.RoleType.ROLE_TYPE_PLAYER;
import static com.huawei.rtc.models.UserInfo.RoleType.ROLE_TYPE_PUBLISER;
import static com.huawei.rtc.utils.RtcEnums.AudioRoute.AUDIO_ROUTE_BLUETOOTH;
import static com.huawei.rtc.utils.RtcEnums.AudioRoute.AUDIO_ROUTE_HEADSET;
import static com.huawei.rtc.utils.RtcEnums.AudioRoute.AUDIO_ROUTE_RECEIVER;
import static com.huawei.rtc.utils.RtcEnums.AudioRoute.AUDIO_ROUTE_SPEAKER;
import static com.huawei.rtc.utils.RtcEnums.SpeakerModel.AUDIO_EARPIECE;
import static com.huawei.rtc.utils.RtcEnums.SpeakerModel.AUDIO_SPEAKER;
import static com.huawei.rtc.utils.RtcEnums.StreamType.STREAM_TYPE_HD;

public class LiveActivity extends BaseActivity {
    private static final String TAG = "LiveActivity";

    private WndArrangeMaker mWndArrangeMaker;
    private ImageView mSwitchCameraBtn;
    private ImageView mMuteRoleChangeBtn;
    private ImageView mMuteAudioBtn;
    private ImageView mMuteVideoBtn;
    private ImageView mAudioRouteBtn;
    private EasyPopup mCirclePop;
    private ImageView roomListBtn;
    private TextView roomListBackTv;
    private TextView membersTv;
    private RecyclerView roomMemberRecyclerView;
    private List<BeanRoomMember> roommemberBeansList = new ArrayList<>();
    private RoomMembersAdapter commentRecyclerAdapter;

    private RtcEngine mHwRtcEngine;
    private int mRole = ROLE_TYPE_JOINER.ordinal();
    private String mChannelId;
    private String mUserId;
    private int mThreshold = 3;
    private int streamSelect;

    SharedPreferences rtcSp;

    private boolean mLeaveManually = false;
    private boolean mOnPauseCalled = false;

    private int toastBottomMargin;//提示框位置

    private UploadDialog uploadDialog;
    private ImageView logUploadBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live_room);

        rtcSp = PrefManager.getPreferences(getApplicationContext());

        // 获取屏幕高度
        toastBottomMargin = getWindowManager().getDefaultDisplay().getHeight() / 7;
        mRole = getIntent().getIntExtra(
                Constants.KEY_ROLE,
                ROLE_TYPE_PLAYER.ordinal());
        mChannelId = getIntent().getStringExtra(Constants.KEY_CHANNELID);
        mUserId = getIntent().getStringExtra(Constants.KEY_USERID);
        streamSelect = rtcSp.getInt(Constants.RTC_PREF_STREAM_SELECT, STREAM_TYPE_HD.ordinal());
        Log.e(TAG, "onCreate: "+streamSelect);

        if (mRole == ROLE_TYPE_PLAYER.ordinal()) {
            mThreshold = 4;
        }

        mHwRtcEngine = ((RtcApplication) getApplication()).getEngine();
        ((RtcApplication) getApplication()).registerEventHandler(this);

        initUI();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    private void initUI() {

        TextView roomName = findViewById(R.id.live_room_name);
        TextView userID = findViewById(R.id.live_room_broadcaster_uid);
        roomName.setText("room id：" + mChannelId);
        userID.setText("user id：" + mUserId);
        roomName.setSelected(true);
        userID.setSelected(true);

        initUserIcon();

        boolean isPlayer = (mRole == ROLE_TYPE_PLAYER.ordinal());

        if (uploadDialog == null) {
            uploadDialog = new UploadDialog(this);
        }

        logUploadBtn = findViewById(R.id.live_btn_log_upload);
        uploadDialog.setCanceledOnTouchOutside(true);

        mSwitchCameraBtn = findViewById(R.id.live_btn_switch_camera);
        mSwitchCameraBtn.setActivated(!isPlayer);

        mMuteRoleChangeBtn= findViewById(R.id.live_btn_role_change);
        mMuteRoleChangeBtn.setActivated(!isPlayer);

        mMuteVideoBtn = findViewById(R.id.live_btn_mute_video);
        mMuteVideoBtn.setActivated(!isPlayer);

        mMuteAudioBtn = findViewById(R.id.live_btn_mute_audio);
        mMuteAudioBtn.setActivated(!isPlayer);

        mAudioRouteBtn = findViewById(R.id.live_btn_audio_route);
        mAudioRouteBtn.setActivated(false);

        roomListBtn = findViewById(R.id.live_btn_roomlist);

        mWndArrangeMaker = findViewById(R.id.live_video_grid_layout);

        if (mRole == ROLE_TYPE_JOINER.ordinal()) {
            startJoin();
        } else if (mRole == ROLE_TYPE_PLAYER.ordinal()) {
            startPlay();
        } else {

            startPublish();
        }
    }

    private SurfaceView prepareRtcVideo(String userId, boolean local, RtcEnums.StreamType type) {
        SurfaceView surface = RtcEngine.createRenderer(getApplicationContext());
        if (local) {
            Log.i(TAG, "HwRtcDemo prepareRtcVideo setupLocalView userid : " + userId);
            mHwRtcEngine.setupLocalView(surface, RtcEnums.ViewMode.VIEW_MODE_CROP);
        } else {
            Log.i(TAG, "HwRtcDemo prepareRtcVideo setupRemoteView userid : " + userId);
            mHwRtcEngine.setupRemoteView(surface, RtcEnums.ViewMode.VIEW_MODE_CROP, type, userId);
        }
        return surface;
    }

    private void removeRtcVideo(String userId, boolean local) {
        if (local) {
            mHwRtcEngine.setupLocalView(null, RtcEnums.ViewMode.VIEW_MODE_CROP);
        } else {
            mHwRtcEngine.setupRemoteView(null, RtcEnums.ViewMode.VIEW_MODE_CROP, RtcEnums.StreamType.values()[streamSelect], userId);
        }
    }

    private void removeRemoteAuxView(String userId) {
        Log.i(Constants.RTC_TAG, "removeRemoteAuxView userId:" +userId);
        RemoteViewType remoteViewType = new RemoteViewType();
        remoteViewType.setUserId(userId);
        remoteViewType.setView(null);
        remoteViewType.setViewMode(RtcEnums.ViewMode.VIEW_MODE_CROP);
        mHwRtcEngine.setupRemoteSubStreamView(remoteViewType);
    }

    public void getRoomMemberPopup(View view) {
        WindowManager wm = (WindowManager) getBaseContext()
                .getSystemService(Context.WINDOW_SERVICE);

        //计算屏幕宽高
        SreenPropertyUtil.getAndroiodScreenProperty(this);

        int width = wm.getDefaultDisplay().getWidth();
        mCirclePop = new EasyPopup(LiveActivity.this)
                .setContentView(R.layout.activity_room_list)
                //      .setAnimationStyle(R.style.CirclePopAnim)
                //是否允许点击PopupWindow之外的地方消失
                .setFocusAndOutsideEnable(true)
                //允许背景变暗
                .setBackgroundDimEnable(true)
                //变暗的透明度(0-1)，0为完全透明
                .setDimValue(1f)
                .setWidth(width)
                .setHeight(SreenPropertyUtil.getHeight_xp(1f))
                .createPopup();
        mCirclePop.showAtLocation(roomListBtn, Gravity.BOTTOM, 0, 0);

        roomMemberRecyclerView = mCirclePop.getView(R.id.recycler_comment);

        roomListBackTv = mCirclePop.getView(R.id.tv_room_list_back);
        membersTv = mCirclePop.getView(R.id.tv_members);
        membersTv.setText("("+roommemberBeansList.size()+")");
        roomListBackTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCirclePop.dismiss();
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                getRoomMemberListWithThread();
            }
        }).start();

    }

    private void getRoomMemberListWithThread() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //此时已在主线程中，可以更新UI了
                // 定义一个线性布局管理器
                LinearLayoutManager manager = new LinearLayoutManager(LiveActivity.this);
                // 设置布局管理器
                roomMemberRecyclerView.setLayoutManager(manager);
                Log.i(TAG, "roommemberBeansList.size(): " + roommemberBeansList.size());
                // 设置adapter
                commentRecyclerAdapter = new RoomMembersAdapter(LiveActivity.this, roommemberBeansList, mThreshold);
                roomMemberRecyclerView.setAdapter(commentRecyclerAdapter);
                // 增加分割线
                roomMemberRecyclerView.addItemDecoration(new DividerItemDecoration(LiveActivity.this, RecyclerView.VERTICAL));//support 包的版本是 25或以上时使用
            }
        });
    }

    private void initUserIcon() {
        Bitmap origin = BitmapFactory.decodeResource(getResources(), R.drawable.my);
        RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(getResources(), origin);
        drawable.setCircular(true);
        ImageView iconView = findViewById(R.id.live_name_board_icon);
        iconView.setImageDrawable(drawable);
    }

    @Override
    protected void onGlobalLayoutCompleted() {
        RelativeLayout topLayout = findViewById(R.id.live_room_top_layout);
        RelativeLayout.LayoutParams params =
                (RelativeLayout.LayoutParams) topLayout.getLayoutParams();
        params.height = mStatusBarHeight + topLayout.getMeasuredHeight();
        topLayout.setLayoutParams(params);
        topLayout.setPadding(0, mStatusBarHeight, 0, 0);
    }

    private void startJoin() {
        SurfaceView surface = prepareRtcVideo(mUserId, true, RtcEnums.StreamType.values()[streamSelect]);
        mWndArrangeMaker.addUserVideoSurface(mUserId, surface, true);
        mMuteAudioBtn.setActivated(true);
        mMuteVideoBtn.setActivated(true);
        mAudioRouteBtn.setActivated(false);
        mHwRtcEngine.setSpeakerModel(AUDIO_EARPIECE);
        roomListBtn.setActivated(true);
    }

    private void startPlay() {
        mMuteAudioBtn.setActivated(false);
        mMuteAudioBtn.setEnabled(false);
        mAudioRouteBtn.setActivated(false);
        mHwRtcEngine.setSpeakerModel(AUDIO_EARPIECE);
        Log.i(TAG, "HwRtcDemo startPlayer mAudioRouteBtn false! ");
        mMuteVideoBtn.setActivated(false);
        mMuteVideoBtn.setEnabled(false);
        mSwitchCameraBtn.setEnabled(false);
        mSwitchCameraBtn.setActivated(false);
        roomListBtn.setActivated(true);
    }

    private void startPublish() {
        SurfaceView surface = prepareRtcVideo(mUserId, true, RtcEnums.StreamType.values()[streamSelect]);
        mWndArrangeMaker.addUserVideoSurface(mUserId, surface, true);
        mMuteRoleChangeBtn.setActivated(false);
        mMuteRoleChangeBtn.setEnabled(false);
        mMuteAudioBtn.setActivated(true);
        mMuteVideoBtn.setActivated(true);
        mAudioRouteBtn.setEnabled(false);
        mAudioRouteBtn.setActivated(false);
        roomListBtn.setEnabled(false);
        roomListBtn.setActivated(false);
    }

    public void renderRemoteUser(String userId, RtcEnums.StreamType type) {
        Log.i(Constants.RTC_TAG, "HwRtcDemo renderRemoteUser userId:" + userId);

        SurfaceView surface = prepareRtcVideo(userId, false, type);
        mWndArrangeMaker.addUserVideoSurface(userId, surface, false);
    }

    public void renderRemoteAuxView(String userId) {
        Log.i(Constants.RTC_TAG, "renderRemoteAuxView userId:" +userId);
        SurfaceView surface = RtcEngine.createRenderer(getApplicationContext());
        RemoteViewType remoteViewType = new RemoteViewType();
        remoteViewType.setUserId(userId);
        remoteViewType.setView(surface);
        remoteViewType.setViewMode(RtcEnums.ViewMode.VIEW_MODE_PAD);
        mHwRtcEngine.setupRemoteSubStreamView(remoteViewType);

        mWndArrangeMaker.addUserVideoSurface("AUX_"+userId, surface, false);
    }

    public void removeRemoteUser(String userId) {
        if (isUserPlaying(userId)) {
            removeRtcVideo(userId, false);
            mWndArrangeMaker.removeUserVideo(userId);
        }
        removeRoomMember(userId);
    }

    public void reRenderLocalUser() {
        Log.i(Constants.RTC_TAG, "renderRemoteUser userId:" + mUserId);
        SurfaceView surface = prepareRtcVideo(mUserId, true, RtcEnums.StreamType.values()[streamSelect]);
        String removeUserId = mWndArrangeMaker.reAddLocalUserVideoSurface(mUserId, surface, true);
        if(removeUserId!=null){
            changePlayState(removeUserId);
        }
    }

    public void removeLocalUser(){
        Log.e(Constants.RTC_TAG, "zhanganl removeLocalUser userId:" + mUserId);
        removeRtcVideo(mUserId, true);
        mWndArrangeMaker.removeUserVideo(mUserId);
    }

    public void unSelectRemoteUser(String userId) {
        if(userId.contains("AUX_")){
            String auxUserId = userId.substring(4);
            Log.i(TAG, "unSelectRemoteUser auxUserId: "+auxUserId );
            removeRemoteAuxView(auxUserId);
        }else{
            removeRtcVideo(userId, false);
        }

        mWndArrangeMaker.unSelectUserVideo(userId);
    }

    public void onHangupClicked(View view) {
        Log.i(TAG, "HwRtcDemo onHangupClicked!");

        mLeaveManually = true;
        finish();
        mHwRtcEngine.leaveRoom();
    }

    public void onSwitchCameraClicked(View view) {
        mHwRtcEngine.switchCamera();
    }


    public void onUploadLog(View view){
        logUploadBtn.setClickable(false);
        handler.sendEmptyMessage(ProgressHandler.START);
        mHwRtcEngine.logUpload();
    }

    public void onChangeRole(View view){
        if (view.isActivated()) {
            mHwRtcEngine.setUserRole(ROLE_TYPE_PLAYER);

            mThreshold = 4;

            mMuteAudioBtn.setEnabled(false);
            mMuteAudioBtn.setActivated(false);
            mMuteVideoBtn.setEnabled(false);
            mMuteVideoBtn.setActivated(false);
            mSwitchCameraBtn.setEnabled(false);
            mSwitchCameraBtn.setActivated(false);

        } else {
            mHwRtcEngine.setUserRole(ROLE_TYPE_JOINER);

            mThreshold = 3;

            mMuteAudioBtn.setEnabled(true);
            mMuteAudioBtn.setActivated(true);
            mMuteVideoBtn.setEnabled(true);
            mMuteVideoBtn.setActivated(true);
            mSwitchCameraBtn.setEnabled(true);
            mSwitchCameraBtn.setActivated(true);

        }
        view.setActivated(!view.isActivated());
    }

    public void onAudioRouteClicked(View view) {
        if (view.isActivated()) {
            mHwRtcEngine.setSpeakerModel(AUDIO_EARPIECE);
        } else {
            mHwRtcEngine.setSpeakerModel(AUDIO_SPEAKER);
        }
        view.setActivated(!view.isActivated());
    }

    public void onMuteAudioClicked(View view) {
        mHwRtcEngine.muteLocalAudio(view.isActivated());
        view.setActivated(!view.isActivated());
    }

    public void onMuteVideoClicked(View view) {
        mHwRtcEngine.muteLocalVideo(view.isActivated());
        view.setActivated(!view.isActivated());
    }

    private boolean needToReturnToMain(RtcEnums.ConnStateTypes state) {
        if (RtcEnums.ConnStateTypes.RTC_CONNE_STATE_FAILED == (state)) {
            return true;
        }
        return false;
    }

    @Override
    public void onError(int s, String s1) {
        final int errcode = s;
        final String msg = s1;

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast toast = Toast.makeText(LiveActivity.this, "errcode:" + errcode + System.getProperty("line.separator") + "msg:" + msg, Toast.LENGTH_SHORT);
                setToast(toast);

                if (RtcConstants.RtcErrorCode.RTC_ERR_CODE_ROOM_STATUS_BUSY == errcode||errcode==RtcConstants.RtcErrorCode.RTC_ERR_CODE_KICK_OFF) {
                    Log.i(TAG, "call leave room");
                    mLeaveManually = true;
                    finish();
                    mHwRtcEngine.leaveRoom();
                }
            }
        });
    }

    @Override
    public void onJoinRoomSuccess(String roomId, String userId) {
        Log.i(TAG, "HwRtcDemo onJoinRoomSuccess roomId:" + roomId + ", userId:" + userId);
    }

    @Override
    public void onLeaveRoom(String roomId, String userId, StatsInfo statsInfo) {
        Log.i(TAG, "HwRtcDemo onLeaveRoom, roomId:" + roomId + ", userId:" + userId);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        });
    }

    @Override
    public void onUserJoined(String roomId, final String userId, String nickname) {
        Log.i(TAG, "HwRtcDemo onUserJoined roomId:" + roomId + ", userId:" + userId + ", nickname:" + nickname);
        if (userId.equals(mUserId) || mRole == ROLE_TYPE_PUBLISER.ordinal()) {
            return;
        }

        mHwRtcEngine.selectVideoFrameOutput(userId);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (IsUserIsExist(userId)) {
                    Log.i(TAG, "HwRtcDemo onUserJoined userId:" + userId + " is exsit");
                    return;
                }

                Toast toast = Toast.makeText(LiveActivity.this, userId + " has joined room", Toast.LENGTH_SHORT);
                setToast(toast);

                if (getNumberOfPlaying() >= mThreshold) {
                    roommemberBeansList.add(new BeanRoomMember(userId, false));//添加房间成员信息
                    if (commentRecyclerAdapter != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                membersTv.setText("("+roommemberBeansList.size()+")");
                                commentRecyclerAdapter.notifyDataSetChanged();
                            }
                        });
                    }
                    return;
                } else {
                    roommemberBeansList.add(new BeanRoomMember(userId, true));//添加房间成员信息
                    if (commentRecyclerAdapter != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                membersTv.setText("("+roommemberBeansList.size()+")");
                                commentRecyclerAdapter.notifyDataSetChanged();
                            }
                        });
                    }
                }

                renderRemoteUser(userId, RtcEnums.StreamType.values()[streamSelect]);

            }
        });
    }

    private boolean isUserPlaying(String userId) {
        Iterator it = roommemberBeansList.iterator();
        while(it.hasNext()) {
            BeanRoomMember beanRoomMember = (BeanRoomMember)it.next();
            if (beanRoomMember.getUserId().equals(userId)) {
                return beanRoomMember.getIsPlaying();
            }
        }
        return false;
    }

    @Override
    public void onUserOffline(String roomId, final String userId, int reason) {
        Log.i(TAG, "HwRtcDemo onUserOffline roomId:" + roomId + ", userId:" + userId + ", reason:" + reason);
        if (userId.equals(mUserId) || mRole == ROLE_TYPE_PUBLISER.ordinal()) {
            return;
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.i(TAG, "HwRtcDemo run removeRemoteUser! ");
                Toast toast = Toast.makeText(LiveActivity.this, userId + " leaves room!", Toast.LENGTH_SHORT);
                setToast(toast);
                removeRemoteUser(userId);

                if (commentRecyclerAdapter != null) {
                    membersTv.setText("("+roommemberBeansList.size()+")");
                    commentRecyclerAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    @Override
    public void onFirstRemoteVideoDecoded(String roomId, final String userId, int width, int height) {
        Log.i(TAG, "HwRtcDemo onFirstRemoteVideoDecoded userId:" + userId + ", roomId:" + roomId + ", width:" + width + ", height:" + height);
    }

    public void onAgreedStreamAvailable(String roomId, final String userId, final RtcEnums.StreamType streamType) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast toast = Toast.makeText(LiveActivity.this, "default stream received: " + userId, Toast.LENGTH_SHORT);
                setToast(toast);
                roommemberBeansList.add(new BeanRoomMember(userId, true));//添加房间成员信息
                renderRemoteUser(userId, streamType);
            }
        });
        Log.i(TAG, "HwRtcDemo onAgreedStreamAvailable userId:" + userId + ", roomId:" + roomId + ", streamType:" + streamType);
    }

    public int getNumberOfPlaying() {
        int num = 0;
        for (int i = 0; i < roommemberBeansList.size(); i++) {
            if (roommemberBeansList.get(i).getIsPlaying()) {
                num++;
            }
        }
        return num;
    }

    public void removeRoomMember(String userId) {
        for (int i = 0; i < roommemberBeansList.size(); i++) {
            Log.i(TAG, "roommemberBeansList.get(i): " + roommemberBeansList.get(i) + " userId:" + userId);
            if (roommemberBeansList.get(i).getUserId().equals(userId)) {
                roommemberBeansList.remove(i);
                break;
            }
        }
    }

    public boolean IsUserIsExist(String userId) {
        for (int i = 0; i < roommemberBeansList.size(); i++) {
            if (roommemberBeansList.get(i).getUserId().equals(userId)) {
                return true;
            }
        }
        return false;
    }

    public void changePlayState(String userId) {
        for (int i = 0; i < roommemberBeansList.size(); i++) {
            if (roommemberBeansList.get(i).getUserId().equals(userId)) {
                if (roommemberBeansList.get(i).getIsPlaying()) {
                    roommemberBeansList.get(i).setIsPlaying(false);
                } else {
                    roommemberBeansList.get(i).setIsPlaying(true);
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        showNormalMoreButtonDialog();
    }

    private void showNormalMoreButtonDialog() {
        AlertDialog.Builder normalMoreButtonDialog = new AlertDialog.Builder(this);
        normalMoreButtonDialog.setTitle("leave room");
        normalMoreButtonDialog.setIcon(R.drawable.logo);
        normalMoreButtonDialog.setMessage("confirm to leave room?");

        //设置按钮
        normalMoreButtonDialog.setPositiveButton("confirm"
                , new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mLeaveManually = true;
                        dialog.dismiss();
                        finish();
                        mHwRtcEngine.leaveRoom();

                    }
                });
        normalMoreButtonDialog.setNegativeButton("cancel"
                , new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        normalMoreButtonDialog.create().show();
    }

    @Override
    public void onConnectionStateChange(RtcEnums.ConnStateTypes var1, RtcEnums.ConnChangeReason var2, String var3) {
        final RtcEnums.ConnStateTypes state = var1;
        final String msg = var3;

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast toast = Toast.makeText(LiveActivity.this, "msg:" + msg, Toast.LENGTH_SHORT);
                setToast(toast);

                if (needToReturnToMain(state)) {
                    finish();
                }
            }
        });
    }

    @Override
    public void onUserRoleChanged(UserInfo.RoleType roleType, UserInfo.RoleType roleType1) {
        Log.e(TAG, "onUserRoleChanged roleType: "+roleType+"roleType1:"+roleType1);

        if(roleType==ROLE_TYPE_JOINER&&roleType1==ROLE_TYPE_PLAYER){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    removeLocalUser();
                }
            });

        }else if(roleType==ROLE_TYPE_PLAYER&&roleType1==ROLE_TYPE_JOINER){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    reRenderLocalUser();
                }
            });

        }
    }

    @Override
    public void onAudioRouteChanged(RtcEnums.AudioRoute audioRoute) {
        Log.e(TAG, "onAudioRouteChanged: "+ audioRoute );
        if(audioRoute==AUDIO_ROUTE_SPEAKER){
            mAudioRouteBtn.setActivated(true);
        }else if(audioRoute==AUDIO_ROUTE_HEADSET||audioRoute==AUDIO_ROUTE_RECEIVER||audioRoute==AUDIO_ROUTE_BLUETOOTH){
            mAudioRouteBtn.setActivated(false);
        }
    }

    @Override
    public void onRenderVideoFrame(String s, String s1, byte[] bytes, int i, int i1, int i2, int i3) {
        Log.e(TAG, "onRenderVideoFrame demo " +"   "+bytes[0]+"   "+bytes[1]+"   "+bytes[2]+"   "+s+"   "+s1+"   "+i+"   "+i1+"   "+i2+"   "+i3);
        try {
            String fileName = "/testyuv_"+s1+"_"+i1+"_"+i2+".yuv";
            writeFile(String.valueOf(Environment.getExternalStorageDirectory())+"/rtcout",fileName,  bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public synchronized static void writeFile(String path, String fileName, byte[] content)
            throws IOException {
        try {
            File f = new File(path);
            if (!f.exists()) {
                f.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(path + fileName,true);
            fos.write(content);
            fos.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onPlaybackAudioFrame(String s, byte[] bytes, int i, int i1, int i2, int i3, int i4) {
        Log.e(TAG, "onPlaybackAudioFrame demo " +"   "+bytes[0]+"   "+bytes[1]+"   "+bytes[2]+"   "+s+"   "+i+"   "+i1+"   "+i2+"   "+i3+"   "+i4);
        try {
            writeFile(String.valueOf(Environment.getExternalStorageDirectory())+"/rtcout","/testpcm.pcm",  bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @SuppressLint("ResourceType")
    @Override
    public void onVideoStats(List<LocalVideoStats> localStats, List<RemoteVideoStats> remoteStats){

    }

    @SuppressLint("ResourceType")
    @Override
    public void onAudioStats(List<LocalAudioStats> list, List<RemoteAudioStats> list1) {

    }

    @Override
    public void onUserSubStreamAvailable(String roomId, final String userId, final boolean available) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (available) {
                    Log.i(TAG, "onUserSubStreamAvailable add userid: " + userId);
                    Toast toast = Toast.makeText(LiveActivity.this, "default stream received: " + userId, Toast.LENGTH_SHORT);
                    setToast(toast);

                    if (getNumberOfPlaying() >= mThreshold) {
                        roommemberBeansList.add(new BeanRoomMember("AUX_"+userId, false));//添加房间成员信息
                        if (commentRecyclerAdapter != null) {
                            membersTv.setText("(" + roommemberBeansList.size() + ")");
                            commentRecyclerAdapter.notifyDataSetChanged();
                        }
                    }else{
                        roommemberBeansList.add(new BeanRoomMember("AUX_"+userId, true));//添加房间成员信息
                        if (commentRecyclerAdapter != null) {
                            membersTv.setText("(" + roommemberBeansList.size() + ")");
                            commentRecyclerAdapter.notifyDataSetChanged();

                        }
                    }
                    renderRemoteAuxView(userId);
                }else{
                    Log.i(TAG, "onUserSubStreamAvailable remove userid: "+userId);
                    Toast toast = Toast.makeText(LiveActivity.this, "AUX_"+userId + " leaves room!", Toast.LENGTH_SHORT);
                    setToast(toast);
                    removeRemoteUser("AUX_"+userId);

                    if (commentRecyclerAdapter != null) {
                        membersTv.setText("("+roommemberBeansList.size()+")");
                        commentRecyclerAdapter.notifyDataSetChanged();
                    }
                }

            }
        });
    }

    @Override
    public void onSubStreamStats(boolean b, LocalVideoStats lcoalStats, RemoteVideoStats remoteStats) {

    }

    @Override
    public void onLogUploadResult(int i) {
        if (i == 0){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(LiveActivity.this,"log upload success",Toast.LENGTH_SHORT).show();
                }
            });
        }else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(LiveActivity.this,"log upload failed",Toast.LENGTH_SHORT).show();
                }
            });
        }
        logUploadBtn.setClickable(true);
    }

    @Override
    public void onLogUploadProgress(int i) {
        Log.e("onLogUploadProgress","onLogUploadProgress"+i );
        Message message = new Message();
        message.arg1 = i;
        message.what = LiveActivity.ProgressHandler.PROGRESS;
        handler.sendMessage(message);
    }

    private LiveActivity.ProgressHandler handler = new LiveActivity.ProgressHandler(this);

    public static class ProgressHandler extends Handler {
        public static final int TOAST = 0X123;

        public static final int START = 0X456;

        public static final int PROGRESS = 0x789;

        WeakReference<LiveActivity> activityWeakReference;

        public ProgressHandler(LiveActivity activity) {
            this.activityWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            UploadDialog uploadDialog = activityWeakReference.get().uploadDialog;
            switch (msg.what) {
                case TOAST:
                    uploadDialog.dismiss();
                    break;
                case START:
                    if (!activityWeakReference.get().isFinishing()) {
                        Log.e("isFinishing()","11111" );
                        uploadDialog.show();
                        uploadDialog.setProgressBar(1);
//                        activityWeakReference.get().logExportBtn.setClickable(false);
                    }else {
                        Log.e("isFinishing()","00000" );
                    }
//                    activityWeakReference.get().logExportBtn.setBackground(activityWeakReference.get().getResources().getDrawable(R.drawable.btn_upload_unclickable_bg));

                    break;
                case PROGRESS:
                    if (msg.arg1 < 100) {
//                        uploadDialog.show();
                        uploadDialog.setProgressBar(msg.arg1);
                    } else {
//                        activityWeakReference.get().logExportBtn.setClickable(true);
//                        activityWeakReference.get().logExportBtn.setBackground(activityWeakReference.get().getResources().getDrawable(R.drawable.btn_upload_bg));
                        uploadDialog.dismiss();
                    }
                default:
                    break;
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();

        if (true == mOnPauseCalled) {
            if (mMuteAudioBtn.isActivated()) {
                mHwRtcEngine.muteLocalAudio(false);
            }

            if (mMuteVideoBtn.isActivated()) {
                mHwRtcEngine.muteLocalVideo(false);
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        if (false == mLeaveManually) {
            if (mMuteAudioBtn.isEnabled()) {
                mHwRtcEngine.muteLocalAudio(true);
            }
            if (mMuteVideoBtn.isEnabled()) {
                mHwRtcEngine.muteLocalVideo(true);
            }
        }
        mOnPauseCalled = true;
    }

    private void setToast(Toast toast){
        // 这里给了一个1/7屏幕高度的y轴偏移量
        toast.setGravity(Gravity.BOTTOM, 0, toastBottomMargin);
        toast.show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ((RtcApplication) getApplication()).removeEventHandler(this);
    }
}
