/**
 * 截图/录像功能 Helper
 * 从 EZRealPlayActivity 拆分出来，负责截图、录像录制的控制和UI更新
 */
package com.videogo.ui.realplay.helper;

import android.Manifest;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.videogo.EzvizApplication;
import com.videogo.exception.BaseException;
import com.videogo.exception.InnerException;
import com.videogo.global.DemoConfig;
import com.videogo.openapi.EZOpenSDKListener;
import com.videogo.ui.realplay.EZRealPlayActivity;
import com.videogo.util.AudioPlayUtil;
import com.videogo.util.EZDateTimeUtil;
import com.videogo.util.EZUtils;
import com.videogo.util.LogUtil;
import com.videogo.util.RotateViewUtil;
import com.videogo.util.Utils;

import java.io.File;

import ezviz.ezopensdk.R;
import ezviz.ezopensdkcommon.common.EZPermissionUtil;

/**
 * 截图/录像功能 Helper
 * 管理截图保存、录像录制的开始/停止、录制计时UI更新
 * <p>
 * 直接持有 Activity 引用，生命周期与 Activity 一致
 */
public class CaptureRecordHelper {

    private static final String TAG = "CaptureRecordHelper";

    private ImageButton mRealPlayCaptureBtn;// 截图按钮
    private ImageButton mRealPlaySnapshotUplaodBtn;// 云录制截图上传按钮
    private View mRealPlayRecordContainer;// 录像容器
    private ImageButton mRealPlayRecordBtn;// 录像未录制状态图标
    private ImageButton mRealPlayRecordStartBtn;// 录像录制中图标
    private LinearLayout mRealPlayRecordLy;// 录像过程中时长显示布局
    private View mRealPlayRecordIv;// 录像过程中的红色小圆点
    private TextView mRealPlayRecordTv;// 录像过程中的录制时长

    private final EZRealPlayActivity mActivity;// Activity 引用
    private AudioPlayUtil mAudioPlayUtil;// 音效工具
    private RotateViewUtil mRecordRotateViewUtil;// 录像图标点击动画效果
    private boolean isRecording = false;// 是否正在录像中
    private int mRecordSecond = 0;// 录制时长（秒）
    private String mCurrentRecordPath = null;// 录像文件保存路径

    public CaptureRecordHelper(EZRealPlayActivity activity) {
        this.mActivity = activity;
        mAudioPlayUtil = AudioPlayUtil.getInstance(activity.getApplication());
        mRecordRotateViewUtil = new RotateViewUtil();
        initView();
    }

    /**
     * 初始化截图/录像相关视图
     */
    private void initView() {
        mRealPlayCaptureBtn = (ImageButton) mActivity.findViewById(R.id.realplay_previously_btn);
        mRealPlaySnapshotUplaodBtn = (ImageButton) mActivity.findViewById(R.id.realplay_snapshot_upload_btn);
        mRealPlayRecordContainer = mActivity.findViewById(R.id.realplay_video_container);
        mRealPlayRecordBtn = (ImageButton) mActivity.findViewById(R.id.realplay_video_btn);
        mRealPlayRecordStartBtn = (ImageButton) mActivity.findViewById(R.id.realplay_video_start_btn);
        mRealPlayRecordLy = (LinearLayout) mActivity.findViewById(R.id.realplay_record_ly);
        mRealPlayRecordIv = mActivity.findViewById(R.id.realplay_record_iv);
        mRealPlayRecordTv = (TextView) mActivity.findViewById(R.id.realplay_record_tv);

        // 截图按钮点击事件
        mRealPlayCaptureBtn.setOnClickListener(v -> {
            // Android 10+（API 29+）通过 MediaStore 保存不需要存储权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                onCapturePicBtnClick();
            } else {
                // Android 9 及以下需要申请 WRITE_EXTERNAL_STORAGE 权限
                EZPermissionUtil.requestPermissions(mActivity,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1001, () -> onCapturePicBtnClick());
            }
        });
        // 录像按钮点击事件
        mRealPlayRecordBtn.setOnClickListener(v -> onRecordBtnClick());
        mRealPlayRecordStartBtn.setOnClickListener(v -> onRecordBtnClick());
        // 云录制截图上传按钮点击事件
        mRealPlaySnapshotUplaodBtn.setOnClickListener(v -> onCapturePicUploadBtnClick());
    }

    // region --- 截图相关 ---

    /**
     * 截图Action
     */
    private void onCapturePicBtnClick() {
        if (mActivity.mEZPlayer == null) {
            return;
        }
        Thread thr = new Thread() {
            @Override
            public void run() {
                mAudioPlayUtil.playAudioFile(AudioPlayUtil.CAPTURE_SOUND);
                Bitmap bmp = (mActivity.mWatermarkHelper.isWaterMarkShow() && !mActivity.isMultiChannelDevice) ?
                        mActivity.mEZPlayer.captureRenderPicture(mActivity.mSurfaceHelper.mRealPlaySv.getWidth(),
                                mActivity.mSurfaceHelper.mRealPlaySv.getHeight()) :
                        mActivity.mEZPlayer.capturePicture();
                saveCapturePictrue(bmp);
                if (mActivity.isMultiChannelDevice) {// 双目设备截图
                    Bitmap bmp2 = mActivity.mEZPlayer.capturePicture(1);
                    saveCapturePictrue(bmp2);
                }
                super.run();
            }
        };
        thr.start();
    }

    private void saveCapturePictrue(Bitmap bmp) {
        if (bmp != null) {
            try {
                final String strCaptureFile = DemoConfig.getCapturesFolder() + "/" + System.currentTimeMillis() +
                        ".jpg";
                LogUtil.e(TAG, "captured picture file path is " + strCaptureFile);

                if (TextUtils.isEmpty(strCaptureFile)) {
                    bmp.recycle();
                    bmp = null;
                    return;
                }
                // 将截图bitmap保存至文件
                EZUtils.saveCapturePictrue(strCaptureFile, bmp);
                // 将文件保存至相册
                EZUtils.savePicture2Album(mActivity, bmp);
                Utils.showToast(mActivity, R.string.already_saved_to_volume);
            } catch (InnerException e) {
                e.printStackTrace();
            } finally {
                if (bmp != null) {
                    bmp.recycle();
                    bmp = null;
                    return;
                }
            }
        } else {
            Utils.showToast(mActivity, "抓图失败, 请重试或检查是否开启了硬件解码");
        }
    }

    /**
     * 云录制截图上传Action
     */
    private void onCapturePicUploadBtnClick() {
        if (mActivity.mEZPlayer == null) {
            return;
        }
        Thread thr = new Thread() {
            @Override
            public void run() {
                Bitmap bmp = mActivity.mEZPlayer.capturePicture();
                if (bmp != null) {
                    try {
                        String storageId = EzvizApplication.getOpenSDK().uploadSDKCloudRecordImage(bmp);
                        if (!TextUtils.isEmpty(storageId)) {
                            mActivity.showCopyDialog("上传成功，storageId:", storageId);
                        }
                    } catch (BaseException e) {
                        Utils.showToast(mActivity, "上传失败" + e.getErrorCode());
                        e.printStackTrace();
                    }
                } else {
                    Utils.showToast(mActivity, "抓图失败, 请重试或检查是否开启了硬件解码");
                }
                super.run();
            }
        };
        thr.start();
    }

    // endregion

    // region --- 录像相关 ---

    /**
     * 录像录制Action
     */
    private void onRecordBtnClick() {
        mActivity.mControlDisplaySec = 0;
        if (isRecording) {
            stopRealPlayRecord();
            return;
        }
        // Android 9 及以下需要申请存储权限才能保存录像到相册
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            EZPermissionUtil.requestPermissions(mActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    1002, () -> startRecord());
        } else {
            startRecord();
        }
    }

    /**
     * 实际开始录像
     */
    private void startRecord() {
        if (mActivity.mEZPlayer != null) {
            /**
             * 此路径必须指定为沙盒路径；不能指定为相册路径，部分机型、新系统上有限制
             * This path must be specified as a sandbox path; Cannot be specified as album path, some models and new
             * systems have restrictions
             */
            final String strRecordFile = DemoConfig.getRecordsFolder() + "/" + System.currentTimeMillis() + ".mp4";
            LogUtil.i(TAG, "recorded video file path is " + strRecordFile);
            // 设置录制回调
            mActivity.mEZPlayer.setStreamDownloadCallback(new EZOpenSDKListener.EZStreamDownloadCallback() {
                @Override
                public void onSuccess(String filepath) {
                    LogUtil.i(TAG, "EZStreamDownloadCallback onSuccess " + filepath);
                    // 将录制的视频保存到相册
                    EZUtils.saveVideo2Album(mActivity, new File(filepath), mRecordSecond);
                    Utils.showToast(mActivity, R.string.already_saved_to_volume);
                }

                @Override
                public void onError(EZOpenSDKListener.EZStreamDownloadError code) {
                    LogUtil.e(TAG, "EZStreamDownloadCallback onError " + code.name());
                }
            });
            boolean result;
            if (mActivity.mWatermarkHelper.isWaterMarkShow() && !mActivity.isMultiChannelDevice) {// 水印录制
                result = mActivity.mEZPlayer.startRenderRecordWithFile(strRecordFile);
            } else {// 普通录制
                result = mActivity.mEZPlayer.startLocalRecordWithFile(strRecordFile);
            }
            if (result) {
                isRecording = true;
                mCurrentRecordPath = strRecordFile;
                mAudioPlayUtil.playAudioFile(AudioPlayUtil.RECORD_SOUND);
                handleRecordSuccess();
            } else {
                handleRecordFail();
            }
        }
    }

    /**
     * 停止录像录制
     */
    public void stopRealPlayRecord() {
        if (mActivity.mEZPlayer == null || !isRecording) {
            return;
        }
        // 设置录像按钮为check状态 | Set the recording button to the check status
        if (mActivity.mOrientation == Configuration.ORIENTATION_PORTRAIT) {
            if (!mActivity.mIsOnStop) {
                mRecordRotateViewUtil.applyRotation(mRealPlayRecordContainer, mRealPlayRecordStartBtn,
                        mRealPlayRecordBtn, 0, 90);
            } else {
                mRealPlayRecordStartBtn.setVisibility(View.GONE);
                mRealPlayRecordBtn.setVisibility(View.VISIBLE);
            }
        } else {
            mRealPlayRecordStartBtn.setVisibility(View.GONE);
            mRealPlayRecordBtn.setVisibility(View.VISIBLE);
        }
        mAudioPlayUtil.playAudioFile(AudioPlayUtil.RECORD_SOUND);
        if (mActivity.mWatermarkHelper.isWaterMarkShow() && !mActivity.isMultiChannelDevice) {// 停止水印录制
            mActivity.mEZPlayer.stopRenderRecord();
        } else {// 停止普通录制
            mActivity.mEZPlayer.stopLocalRecord();
        }
        // 计时按钮不可见 | The timed button is not visible
        mRealPlayRecordLy.setVisibility(View.GONE);
        isRecording = false;
    }

    /**
     * 录像录制启动成功后UI刷新
     */
    private void handleRecordSuccess() {
        if (mActivity.mCameraInfo == null) {
            return;
        }
        if (!mActivity.mIsOnStop) {
            mRecordRotateViewUtil.applyRotation(mRealPlayRecordContainer, mRealPlayRecordBtn, mRealPlayRecordStartBtn
                    , 0, 90);
        } else {
            mRealPlayRecordBtn.setVisibility(View.GONE);
            mRealPlayRecordStartBtn.setVisibility(View.VISIBLE);
        }
        isRecording = true;
        mRealPlayRecordLy.setVisibility(View.VISIBLE);
        mRealPlayRecordTv.setText("00:00");
        mRecordSecond = 0;
    }

    /**
     * 录像录制启动失败后UI刷新
     */
    private void handleRecordFail() {
        Utils.showToast(mActivity, R.string.remoteplayback_record_fail);
        if (isRecording) {
            stopRealPlayRecord();
        }
    }

    // endregion

    // region --- 状态查询与UI更新 ---

    /**
     * 是否正在录像中
     */
    public boolean isRecording() {
        return isRecording;
    }

    /**
     * 录像计时递增（Timer 每秒调用）
     */
    public void incrementRecordSecond() {
        mRecordSecond++;
    }

    /**
     * 录像过程中计时UI更新
     */
    public void updateRecordTime() {
        if (mRealPlayRecordIv.getVisibility() == View.VISIBLE) {
            mRealPlayRecordIv.setVisibility(View.INVISIBLE);
        } else {
            mRealPlayRecordIv.setVisibility(View.VISIBLE);
        }
        mRealPlayRecordTv.setText(EZDateTimeUtil.convToMinSec(mRecordSecond));
    }

    /**
     * 更新录像按钮的可见状态（屏幕方向切换时调用）
     */
    public void updateRecordBtnVisibility() {
        if (isRecording) {
            mRealPlayRecordBtn.setVisibility(View.GONE);
            mRealPlayRecordStartBtn.setVisibility(View.VISIBLE);
        } else {
            mRealPlayRecordBtn.setVisibility(View.VISIBLE);
            mRealPlayRecordStartBtn.setVisibility(View.GONE);
        }
    }

    /**
     * 设置截图/录像按钮可用状态
     */
    public void setButtonsEnabled(boolean captureEnabled, boolean recordEnabled, boolean uploadEnabled) {
        mRealPlayCaptureBtn.setEnabled(captureEnabled);
        mRealPlayRecordBtn.setEnabled(recordEnabled);
        mRealPlaySnapshotUplaodBtn.setEnabled(uploadEnabled);
    }

    // endregion
}
