package com.ez.ertc.meeting.presenter;

import android.text.TextUtils;

import com.ez.ertc.meeting.bean.ErtcAudioStatusBean;
import com.ez.ertc.meeting.constant.MtSets;
import com.ez.ertcmeeting.bean.DeviceState;
import com.ez.ertcmeeting.bean.UserAccount;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public
/**
 * 音量回调、语音激励、正在说话等
 *
 * @author xiezuoyuan
 * @time 2022/4/1 14:54
 */
class ErtcAudioStatusCallbackImpl {
    private ErtcRoomPresenter roomPresenter;
    private static final int VOICE_STIMULATION_GAP = 3000;//语音激励间隔
    private long mVoiceStimulationTime;//语音激励时间记录
    private Map<String, AudioFlowRunnable> mAudioFlowRunnableMap = new HashMap<>();
    private List<String> mNamesList = new ArrayList<>();
    private List<String> mNamesListTemp = new ArrayList<>();

    private Comparator<ErtcAudioStatusBean> comparator = new Comparator<ErtcAudioStatusBean>() {
        @Override
        public int compare(ErtcAudioStatusBean o1, ErtcAudioStatusBean o2) {
            return o1.getLevel() - o2.getLevel();
        }
    };

    public ErtcAudioStatusCallbackImpl(ErtcRoomPresenter roomPresenter) {
        this.roomPresenter = roomPresenter;
    }

    private boolean listSame() {
        if (mNamesList.size() == mNamesListTemp.size()) {
            for (int i = 0; i < mNamesList.size(); i++) {
                if (!TextUtils.equals(mNamesList.get(i), mNamesListTemp.get(i))) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    /**
     * 此方法在子线程执行
     * @param list
     */
    public void onAudioStatus(List<ErtcAudioStatusBean> list) {
        if (list != null) {
            //动态显示音频能量
            for (ErtcAudioStatusBean statusBean : list) {
                int level = statusBean.getLevel();
                level = Math.max(level, 0);
                level = Math.min(level, 100);
                //// roomPresenter.mMyAccount.getId() == EzmHelper.getInstance().getAccountData().account.id
                if (statusBean.getUserId().equals(roomPresenter.mMyAccount.getUserId()) || roomPresenter.mGroupView.hasMember(statusBean.getUserId())) {
                    AudioFlowRunnable audioFlowRunnable = mAudioFlowRunnableMap.get(statusBean.getUserId());
                    if (audioFlowRunnable == null) {
                        audioFlowRunnable = new AudioFlowRunnable();
                        mAudioFlowRunnableMap.put(statusBean.getUserId(), audioFlowRunnable);
                    }
                    audioFlowRunnable.set(statusBean.getUserId(), level);
                    roomPresenter.mView.getScreenTextureView().post(audioFlowRunnable);
                }
            }
            //显示正在说话的人
            if (MtSets.isAudioDisplay()) {
                mNamesListTemp.clear();
                Collections.sort(list, comparator);
                for (ErtcAudioStatusBean statusBean : list) {
                    if (statusBean.getLevel() > 0)
                        mNamesListTemp.add(statusBean.getUserId());
                }
                if (!listSame()) {
                    mNamesList.clear();
                    mNamesList.addAll(mNamesListTemp);
                }
            }
            //语音激励满足的条件
            //1、语音激励开启
            //2、无人在共享
            //3、3秒一次回调
            if (roomPresenter.mIsVoiceStimulation
                    && roomPresenter.mSharingDesktopUserId.isEmpty()
                    && System.currentTimeMillis() - mVoiceStimulationTime >= VOICE_STIMULATION_GAP
                    && list.size() > 0) {
                mVoiceStimulationTime = System.currentTimeMillis();
                ErtcAudioStatusBean audioStatusBean = null;
                for (ErtcAudioStatusBean bean : list) {
                    if (audioStatusBean == null || bean.getLevel() > audioStatusBean.getLevel()) {
                        audioStatusBean = bean;
                    }
                }
                if (audioStatusBean != null && audioStatusBean.getLevel() > 0) {
                    synchronized (ErtcRoomPresenter.sAccountList) {
                        for (final UserAccount account : ErtcRoomPresenter.sAccountList) {
                            if (account.getUserId().equals(audioStatusBean.getUserId()) && !account.getUserId().equals(roomPresenter.mScreenAccount.getUserId())) {
                                roomPresenter.mView.getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        roomPresenter.mGroupView.notifySwitchToScreen(account);
                                    }
                                });
                                return;
                            }
                        }
                    }
                }
            }
        }
    }

    private class AudioFlowRunnable implements Runnable {
        private String userId;
        private int level;

        public AudioFlowRunnable() {
        }

        private void set(String userId, int level) {
            this.userId = userId;
            this.level = level;
        }

        @Override
        public void run() {
            if (userId.equals(roomPresenter.mMyAccount.getUserId()) && roomPresenter.mMyAccount.getAudioStatus() == DeviceState.DS_Active.getValue()) {
                roomPresenter.mView.setSelfAudioLevel(level);
                roomPresenter.mGroupView.setSelfAudioLevel(level);
            }
            if (userId.equals(roomPresenter.mScreenAccount.getUserId()) && roomPresenter.mScreenAccount.getAudioStatus() == DeviceState.DS_Active.getValue()) {
                roomPresenter.mView.setScreenAudioLevel(level);
            }
            roomPresenter.mGroupView.setMemberAudioLevel(userId, level);
            level = level - 12;
            if (level >= 40) {//音量最低是0-40
                roomPresenter.mView.getScreenTextureView().postDelayed(this, 100);
            }
        }
    }
}
