/**
 * 倍速控制 Helper
 * 从 EZPlayBackListActivity 拆分出来，负责倍速按钮、倍速选择弹框、设置倍速等逻辑
 */
package com.videogo.ui.playback.helper;

import android.view.View;
import android.widget.Button;

import com.videogo.openapi.EZConstants;
import com.videogo.ui.common.EZBusinessTool;
import com.videogo.ui.playback.EZPlayBackListActivity;
import com.videogo.ui.playback.RemoteListContant;
import com.videogo.util.Utils;
import com.videogo.widget.bottommenu.BottomMenuFragment;

import java.util.Collections;
import java.util.List;

import ezviz.ezopensdk.R;

/**
 * 倍速控制 Helper
 * 管理倍速按钮、云录像/SD卡录像倍速选择底部弹框、设置倍速
 * <p>
 * 直接持有 Activity 引用，生命周期与 Activity 一致
 */
public class PlaybackRateHelper {

    private static final String TAG = "PlaybackRateHelper";

    private Button playbackRateBtn;// 倍数设置按钮

    private final EZPlayBackListActivity mActivity;// Activity 引用

    public PlaybackRateHelper(EZPlayBackListActivity activity) {
        this.mActivity = activity;
        initView();
    }

    /**
     * 初始化倍速相关视图
     */
    private void initView() {
        playbackRateBtn = (Button) mActivity.findViewById(R.id.btn_change_playback_rate);
        playbackRateBtn.setOnClickListener(v -> onPlaybackRateClick(v));
    }

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

    /**
     * 倍数设置按钮Click，弹出倍数设置选项框
     */
    public void onPlaybackRateClick(View view) {
        if (mActivity.mRecordType == RemoteListContant.TYPE_LOCAL) {
            showSDCardRateBottomMenu(view);
        } else {
            showCloudRateBottomMenu(view);
        }
    }

    /**
     * 设置倍速按钮可用状态
     */
    public void setPlaybackRateBtnEnabled(boolean enabled) {
        playbackRateBtn.setEnabled(enabled);
        // 倍数按钮文字颜色跟随状态变化
        playbackRateBtn.setTextColor(enabled ? 0xD9FFFFFF : 0x4DFFFFFF);
    }

    /**
     * 重置倍速按钮文本为1倍
     */
    public void resetRateText() {
        playbackRateBtn.setText("1倍");
    }

    /**
     * 获取倍速按钮（供外部 measure 等操作使用）
     */
    public Button getPlaybackRateBtn() {
        return playbackRateBtn;
    }

    // endregion

    // region --- 私有方法 ---

    /**
     * 显示云录像倍速选择底部弹框
     */
    private void showCloudRateBottomMenu(View view) {
        List<EZConstants.EZPlaybackRate> rates = EZBusinessTool.getCloudPlaybackRates();
        List<String> rateStrings = EZBusinessTool.getCloudPlaybackRateStrings();
        Collections.reverse(rates);
        Collections.reverse(rateStrings);

        String currentRateText = ((Button) view).getText().toString();
        new BottomMenuFragment(mActivity)
                .setHeadTitle(mActivity.getResources().getString(R.string.playback_rate_select))
                .addMenuItems(rateStrings)
                .setSelectContent(currentRateText)
                .setOnItemClickListener(position -> {
                    EZConstants.EZPlaybackRate targetRate = rates.get(position);
                    String targetRateStr = rateStrings.get(position);
                    setPlaybackRate(targetRate, targetRateStr);
                    ((Button) view).setText(targetRateStr);
                })
                .show();
    }

    /**
     * 显示SD卡录像倍速选择底部弹框
     */
    private void showSDCardRateBottomMenu(View view) {
        int streamFetchType = mActivity.mPlaybackPlayer.getStreamFetchType();
        List<EZConstants.EZPlaybackRate> rates = EZBusinessTool.getSDCardPlaybackRates(mActivity.mDeviceInfo, mActivity.mCameraInfo, streamFetchType);
        List<String> rateStrings = EZBusinessTool.getSDCardPlaybackRateStrings(mActivity.mDeviceInfo, mActivity.mCameraInfo, streamFetchType);
        if (rates == null || rates.isEmpty()) {
            Utils.showToast(mActivity, R.string.device_playbackrate_not_support);
            return;
        }
        Collections.reverse(rates);
        Collections.reverse(rateStrings);

        String currentRateText = ((Button) view).getText().toString();
        new BottomMenuFragment(mActivity)
                .setHeadTitle(mActivity.getResources().getString(R.string.playback_rate_select))
                .addMenuItems(rateStrings)
                .setSelectContent(currentRateText)
                .setOnItemClickListener(position -> {
                    EZConstants.EZPlaybackRate targetRate = rates.get(position);
                    String targetRateStr = rateStrings.get(position);
                    setPlaybackRate(targetRate, targetRateStr);
                    ((Button) view).setText(targetRateStr);
                })
                .show();
    }

    /**
     * 设置倍速（耗时任务，子线程执行）
     */
    private void setPlaybackRate(EZConstants.EZPlaybackRate targetRateEnum, String targetRateWithX) {
        // 切换到指定倍速，倍数设置为耗时任务，需要在子线程中执行
        new Thread(() -> {
            if (!mActivity.mPlaybackPlayer.setPlaybackRate(targetRateEnum)) {
                Utils.showToast(mActivity, "failed to change to " + targetRateWithX);
            }
        }).start();
    }

    // endregion
}
