/**
 * 清晰度设置功能 Helper
 * 从 EZRealPlayActivity 拆分出来，负责清晰度设置、自动清晰度管理、清晰度弹窗展示
 */
package com.videogo.ui.realplay.helper;

import android.os.SystemClock;
import android.widget.Button;

import com.videogo.EzvizApplication;
import com.videogo.exception.BaseException;
import com.videogo.global.ValueKeys;
import com.videogo.openapi.EZConstants.EZVideoLevel;
import com.videogo.openapi.bean.EZDeviceDetailPublicInfo;
import com.videogo.openapi.bean.EZVideoQualityInfo;
import com.videogo.ui.common.EZBusinessTool;
import com.videogo.ui.realplay.EZRealPlayActivity;
import com.videogo.util.ConnectionDetector;
import com.videogo.util.LogUtil;
import com.videogo.util.SpTool;
import com.videogo.util.Utils;
import com.videogo.widget.WaitDialog;
import com.videogo.widget.bottommenu.BottomMenuFragment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import ezviz.ezopensdk.R;

/**
 * 清晰度设置功能 Helper
 * 管理清晰度切换、自动清晰度升降档、清晰度设置弹窗
 *
 * 直接持有 Activity 引用，生命周期与 Activity 一致
 */
public class VideoQualityHelper {

    private static final String TAG = "VideoQualityHelper";

    private Button mRealPlayQualityBtn;// 清晰度按钮

    private final EZRealPlayActivity mActivity;// Activity 引用
    private WaitDialog mWaitDialog;// 设置清晰度 loading dialog
    private boolean isQulityModeAuto = false;// 当前设备本地清晰度 是否是"自动"
    private EZVideoLevel mCurrentQulityMode = EZVideoLevel.VIDEO_LEVEL_HD;// 当前设备清晰度，默认高清
    private EZDeviceDetailPublicInfo mDeviceDetailPublicInfo;// 取流详情数据

    public VideoQualityHelper(EZRealPlayActivity activity) {
        this.mActivity = activity;
        mWaitDialog = new WaitDialog(activity, android.R.style.Theme_Translucent_NoTitleBar);
        initView();
    }

    private void initView() {
        mRealPlayQualityBtn = (Button) mActivity.findViewById(R.id.realplay_quality_btn);
        mRealPlayQualityBtn.setOnClickListener(v -> openQualityWindow());
    }

    // region --- 公开方法 ---

    /**
     * 初始化清晰度状态（在 initData 中调用）
     * @param isAutoMode 是否是自动清晰度模式
     */
    public void setQualityModeAuto(boolean isAutoMode) {
        this.isQulityModeAuto = isAutoMode;
    }

    /**
     * 是否是自动清晰度模式
     */
    public boolean isQulityModeAuto() {
        return isQulityModeAuto;
    }

    /**
     * 获取当前清晰度
     */
    public EZVideoLevel getCurrentQulityMode() {
        return mCurrentQulityMode;
    }

    /**
     * 设置当前清晰度（外部更新时使用）
     */
    public void setCurrentQulityMode(EZVideoLevel mode) {
        this.mCurrentQulityMode = mode;
    }

    /**
     * 设置设备详情数据
     */
    public void setDeviceDetailPublicInfo(EZDeviceDetailPublicInfo info) {
        this.mDeviceDetailPublicInfo = info;
    }

    /**
     * 获取设备详情数据
     */
    public EZDeviceDetailPublicInfo getDeviceDetailPublicInfo() {
        return mDeviceDetailPublicInfo;
    }

    /**
     * 设置视频清晰度UI
     */
    public void setVideoLevelUI() {
        if (mActivity.mCameraInfo == null || mActivity.mEZPlayer == null || mActivity.mDeviceInfo == null) {
            return;
        }
        mRealPlayQualityBtn.setEnabled(mActivity.mDeviceInfo.getStatus() == 1);

        /**************
         * 本地数据保存 需要更新之前获取到的设备列表信息，开发者自己设置
         *
         * Local data saved need to be updated before the obtained device list information, the developer's own settings
         * *********************/
        mActivity.mCameraInfo.setVideoLevel(mCurrentQulityMode.getVideoLevel());
        mRealPlayQualityBtn.setText(EZBusinessTool.getDeviceQualityTitle(mActivity, mCurrentQulityMode.getVideoLevel()));
    }

    /**
     * 清晰度设置成功后处理
     */
    public void handleSetVideoModeSuccess() {
        setVideoLevelUI();
        try {
            mWaitDialog.setWaitText(null);
            mWaitDialog.dismiss();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 停止对讲 Stop talk
        mActivity.mVoiceTalkHelper.closeTalkPopupWindow(true);
        // 停止播放 Stop play
        mActivity.playerStopRealPlay();
        SystemClock.sleep(500);
        // 开始播放 Start play
        mActivity.playerStartRealPlay();
    }

    /**
     * 清晰度设置失败后处理
     */
    public void handleSetVideoModeFail(int errorCode) {
        setVideoLevelUI();
        try {
            mWaitDialog.setWaitText(null);
            mWaitDialog.dismiss();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Utils.showToast(mActivity, R.string.realplay_set_vediomode_fail, errorCode);
    }

    /**
     * 打开清晰度设置弹出框
     */
    public void openQualityWindow() {
        if (mActivity.mEZPlayer == null) {
            return;
        }
        boolean isSupportDeviceAutoVideolevel = EZBusinessTool.isSupportDeviceAutoVideolevel(mActivity.mDeviceInfo, mActivity.mCameraInfo);
        // 当前清晰度
        String currentVideoQuality = EZBusinessTool.getDeviceQualityTitle(mActivity, mCurrentQulityMode.getVideoLevel());

        List<EZVideoQualityInfo> videoQualityInfos = Arrays.asList(
                new EZVideoQualityInfo(mActivity.getResources().getString(R.string.quality_flunet), EZVideoLevel.VIDEO_LEVEL_FLUNET.getVideoLevel()),
                new EZVideoQualityInfo(mActivity.getResources().getString(R.string.quality_balanced), EZVideoLevel.VIDEO_LEVEL_BALANCED.getVideoLevel()),
                new EZVideoQualityInfo(mActivity.getResources().getString(R.string.quality_hd), EZVideoLevel.VIDEO_LEVEL_HD.getVideoLevel()));
        // 如果设备有上报清晰度数据，使用上报的数据
        if (mDeviceDetailPublicInfo != null && mDeviceDetailPublicInfo.videoQualityInfos != null) {
            videoQualityInfos = mDeviceDetailPublicInfo.videoQualityInfos;
        }

        List<String> videoQualitys = new ArrayList<>();
        for (int i = 0; i < videoQualityInfos.size(); i++) {
            String qualityName = videoQualityInfos.get(i).getVideoQualityName();
            videoQualitys.add(qualityName != null ? qualityName : "");
        }
        // 如果设备支持，清晰度列表中加入"自动"选项 或 "自动(具体清晰度)"
        if (isSupportDeviceAutoVideolevel) {
            if (isQulityModeAuto) {
                videoQualitys.add(mActivity.getResources().getString(R.string.quality_auto_select, currentVideoQuality));
            } else {
                videoQualitys.add(mActivity.getResources().getString(R.string.quality_auto));
            }
        }
        List<EZVideoQualityInfo> finalVideoQualityInfos = videoQualityInfos;
        // 自动清晰度时文本：自动(具体清晰度)    非自动清晰度时文本：具体清晰度
        String selectVideoQuality =
                isQulityModeAuto ? mActivity.getResources().getString(R.string.quality_auto_select, currentVideoQuality) : currentVideoQuality;
        new BottomMenuFragment(mActivity)
                .setHeadTitle(mActivity.getResources().getString(R.string.quality_select_tip))
                .addMenuItems(videoQualitys)
                .setSelectContent(selectVideoQuality)
                .setOnItemClickListener(position -> {
                    isQulityModeAuto = videoQualitys.get(position).contains(mActivity.getResources().getString(R.string.quality_auto));
                    // 本地缓存设备当前状态是否是"自动清晰度"，不支持的不用管理状态
                    if (isSupportDeviceAutoVideolevel) {
                        SpTool.storeBooleanValue(ValueKeys.QUALITY_AUTO + "_" + mActivity.mCameraInfo.getDeviceSerial(), isQulityModeAuto);
                    }
                    // 选择"自动"，重新取流，接收到通知消息后再切换清晰度；
                    if (isQulityModeAuto) {
                        // 停止播放 Stop play
                        mActivity.playerStopRealPlay();
                        SystemClock.sleep(500);
                        mActivity.mEZPlayer.enableDeviceAutoVideoLevel();
                        // 开始播放 Start play
                        mActivity.playerStartRealPlay();
                    } else {// 选择具体的清晰度时，切换清晰度
                        com.videogo.openapi.bean.EZCameraInfo tempCameraInfo = new com.videogo.openapi.bean.EZCameraInfo();
                        tempCameraInfo.setVideoLevel(finalVideoQualityInfos.get(position).getVideoLevel());
                        setQualityMode(tempCameraInfo.getVideoLevel());
                    }
                })
                .show();
    }

    /**
     * 设置清晰度请求
     */
    public void setQualityMode(final EZVideoLevel mode) {
        // 检查网络是否可用 Check if the network is available
        if (!ConnectionDetector.isNetworkAvailable(mActivity)) {
            // 提示没有连接网络 Prompt not to connect to the network
            Utils.showToast(mActivity, R.string.realplay_set_fail_network);
            return;
        }

        if (mActivity.mEZPlayer != null) {
            mWaitDialog.setWaitText(mActivity.getString(R.string.setting_video_level));
            mWaitDialog.show();

            Thread thr = new Thread(() -> {
                try {
                    EzvizApplication.getOpenSDK().setVideoLevel(
                            mActivity.mCameraInfo.getDeviceSerial(), mActivity.mCameraInfo.getCameraNo(), mode.getVideoLevel());
                    mCurrentQulityMode = mode;
                    mActivity.mHandler.post(() -> handleSetVideoModeSuccess());
                    LogUtil.i(TAG, "setQualityMode success");
                } catch (BaseException e) {
                    e.printStackTrace();
                    mActivity.mHandler.post(() -> handleSetVideoModeFail(0));
                    LogUtil.i(TAG, "setQualityMode fail");
                }
            });
            thr.start();
        }
    }

    /**
     * 设置自动清晰度请求（清晰度升降档时调用）
     */
    public void setQualityModeAuto(final EZVideoLevel mode) {
        if (mActivity.mEZPlayer != null) {
            Thread thr = new Thread(() -> {
                try {
                    EzvizApplication.getOpenSDK().setVideoLevelAuto(mActivity.mCameraInfo.getDeviceSerial(),
                            mActivity.mCameraInfo.getCameraNo(), mode.getVideoLevel());
                    mCurrentQulityMode = mode;
                    mActivity.mHandler.post(() -> mActivity.getDeviceDetailInfoAndRefreshUI());
                    LogUtil.i(TAG, "setQualityModeAuto success");
                } catch (BaseException e) {
                    e.printStackTrace();
                    LogUtil.i(TAG, "setQualityModeAuto fail");
                    // 失败不用处理
                }
            });
            thr.start();
        }
    }

    /**
     * 设置清晰度按钮可用状态
     */
    public void setQualityBtnEnabled(boolean enabled) {
        mRealPlayQualityBtn.setEnabled(enabled);
    }

    /**
     * 开启自动清晰度（Surface 创建后调用）
     */
    public void enableAutoVideoLevelIfNeeded() {
        if (isQulityModeAuto) {
            mActivity.mEZPlayer.enableDeviceAutoVideoLevel();
        }
    }

    /**
     * 尝试自动升降档清晰度（录制中不切换，涉及分辨率变化会影响转码）
     * @param isImprove true=升档，false=降档
     * @param isRecording 是否正在录像
     */
    public void tryAutoAdjustLevel(boolean isImprove, boolean isRecording) {
        if (!isQulityModeAuto || isRecording) {
            return;
        }
        if (isImprove) {
            EZVideoLevel higherVideoLevel = EZBusinessTool.getHigherVideoLevel(mCurrentQulityMode, mDeviceDetailPublicInfo);
            if (higherVideoLevel.getVideoLevel() > mCurrentQulityMode.getVideoLevel()) {
                setQualityModeAuto(higherVideoLevel);
            }
        } else {
            EZVideoLevel lowerVideoLevel = EZBusinessTool.getLowerVideoLevel(mCurrentQulityMode, mDeviceDetailPublicInfo);
            if (lowerVideoLevel.getVideoLevel() < mCurrentQulityMode.getVideoLevel()) {
                setQualityModeAuto(lowerVideoLevel);
            }
        }
    }

    // endregion
}
