/**
 * AI云存储功能 Helper
 * 从 EZPlayBackListActivity 拆分出来，负责AI云存储按钮、视图创建/显示/隐藏/释放、回调处理
 */
package com.videogo.ui.playback.helper;

import android.text.TextUtils;
import android.widget.FrameLayout;
import android.widget.ImageButton;

import com.videogo.aicloud.EZAICloudStorageView;
import com.videogo.openapi.bean.EZCloudRecordFile;
import com.videogo.ui.playback.EZPlayBackListActivity;
import com.videogo.ui.playback.RemoteListContant;
import com.videogo.ui.playback.bean.ClickedListItem;
import com.videogo.util.DataManager;
import com.videogo.util.LogUtil;
import com.videogo.util.VerifyCodeInput;

import ezviz.ezopensdk.R;

import static com.videogo.EzvizApplication.getOpenSDK;

/**
 * AI云存储功能 Helper
 * 管理AI云存储按钮点击、视图的创建/显示/隐藏/释放、OnAICloudStorageCallback回调
 *
 * 直接持有 Activity 引用，生命周期与 Activity 一致
 */
public class AICloudStorageHelper implements EZAICloudStorageView.OnAICloudStorageCallback {

    private static final String TAG = "AICloudStorageHelper";

    private ImageButton mAICloudStorageBtn;// AI云存储按钮
    private FrameLayout mAICloudStorageContainer;// AI云存储UI容器
    private EZAICloudStorageView mAICloudStorageView;// AI云存储视图管理器

    private boolean mIsAICloudStoragePlayback = false;// 当前播放是否由AI云存储触发

    private final EZPlayBackListActivity mActivity;// Activity 引用

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

    /**
     * 初始化AI云存储相关视图
     */
    private void initView() {
        mAICloudStorageBtn = (ImageButton) mActivity.findViewById(R.id.btn_ai_cloud_storage);
        mAICloudStorageContainer = (FrameLayout) mActivity.findViewById(R.id.ai_cloud_storage_container);
        mAICloudStorageBtn.setOnClickListener(v -> onAICloudStorageBtnClick());
    }

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

    /**
     * AI云存储按钮点击处理
     */
    private void onAICloudStorageBtnClick() {
        LogUtil.d(TAG, "AI云存储按钮点击");
        if (mAICloudStorageView != null && mAICloudStorageView.isShowing()) {
            mAICloudStorageView.hide();// 已展示则隐藏
        } else if (mAICloudStorageView != null) {
            mAICloudStorageView.resume();// 已创建过，恢复展示（错误状态会重新请求接口）
        } else {
            // 首次创建，调用EZOpenSDK的API展示AI云存储
            String cachedVerifyCode = DataManager.getInstance().getDeviceSerialVerifyCode(mActivity.mCameraInfo.getDeviceSerial());
            mAICloudStorageView = getOpenSDK().showAICloudStorage(mActivity,
                    mAICloudStorageContainer, mActivity.mCameraInfo.getDeviceSerial(), mActivity.mCameraInfo.getCameraNo(), cachedVerifyCode);
            mAICloudStorageView.setCallback(this);
        }
    }

    /**
     * 设置当前播放是否由AI云存储触发
     */
    public void setAICloudStoragePlayback(boolean isAICloudStoragePlayback) {
        mIsAICloudStoragePlayback = isAICloudStoragePlayback;
    }

    /**
     * 获取当前播放是否由AI云存储触发
     */
    public boolean isAICloudStoragePlayback() {
        return mIsAICloudStoragePlayback;
    }

    /**
     * 播放成功时通知AI云存储页面显示播放动画
     */
    public void notifyPlaybackStarted() {
        if (mIsAICloudStoragePlayback && mAICloudStorageView != null) {
            mAICloudStorageView.updatePlaybackState(true);
            // 如果有加密封面尚未加载（用户之前取消过验证码），此时验证码已获取，刷新封面
            if (mAICloudStorageView.hasEncryptedCoversNotLoaded()) {
                mAICloudStorageView.reloadEncryptedCovers(DataManager.getInstance().getDeviceSerialVerifyCode(mActivity.mCameraInfo.getDeviceSerial()));
            }
        }
    }

    /**
     * 播放完成时通知AI云存储页面重置播放图标
     */
    public void notifyPlaybackFinished() {
        if (mIsAICloudStoragePlayback && mAICloudStorageView != null) {
            mAICloudStorageView.updatePlaybackState(false);
            mIsAICloudStoragePlayback = false;
        }
    }

    /**
     * 释放AI云存储资源（onDestroy时调用）
     */
    public void release() {
        if (mAICloudStorageView != null) {
            mAICloudStorageView.releaseView();
            mAICloudStorageView = null;
        }
    }

    // endregion

    // region --- OnAICloudStorageCallback 回调 ---

    @Override
    public void onAICloudRecordFileClick(EZCloudRecordFile recordFile) {
        LogUtil.d(TAG, "AI云录像片段点击，开始播放: fileId=" + recordFile.getFileId());
        mIsAICloudStoragePlayback = true;
        mActivity.stopCurrentPlayback();
        // 设置播放进度UI
        long beginTime = recordFile.getStartTime() != null ? recordFile.getStartTime().getTimeInMillis() : 0;
        long endTime = recordFile.getStopTime() != null ? recordFile.getStopTime().getTimeInMillis() : 0;
        mActivity.setPlaybackProgressUI(beginTime, endTime);
        // 赋值 currentClickItemFile，供计时器 playBoxToolRefresh 更新进度条使用
        mActivity.currentClickItemFile = new ClickedListItem(0, RemoteListContant.TYPE_CLOUD, beginTime, endTime, 0);
        // 设置云录像信息并启动播放
        mActivity.mDeviceRecordInfo = null;
        mActivity.mCloudRecordInfo = recordFile;
        mActivity.mRecordType = RemoteListContant.TYPE_CLOUD;
        mActivity.startPlaybackByRecordCategory();
    }

    @Override
    public void onAICloudStorageViewNeedVerifyCode() {
        LogUtil.d(TAG, "AI云存储封面加密，需要验证码");
        // 先查本地缓存是否已有该设备的验证码
        String cachedVerifyCode = DataManager.getInstance().getDeviceSerialVerifyCode(mActivity.mCameraInfo.getDeviceSerial());
        if (!TextUtils.isEmpty(cachedVerifyCode)) {
            LogUtil.d(TAG, "AI云存储封面使用缓存验证码");
            if (mAICloudStorageView != null) {
                mAICloudStorageView.reloadEncryptedCovers(cachedVerifyCode);
            }
            return;
        }
        // 缓存中无验证码，弹出输入框让用户输入
        VerifyCodeInput.VerifyCodeInputDialog(mActivity, verifyCode -> {
            LogUtil.d(TAG, "AI云存储封面验证码: " + verifyCode);
            DataManager.getInstance().setDeviceSerialVerifyCode(mActivity.mCameraInfo.getDeviceSerial(), verifyCode);
            if (mActivity.mPlaybackPlayer != null) {
                mActivity.mPlaybackPlayer.setPlayVerifyCode(verifyCode);
            }
            if (mAICloudStorageView != null) {
                mAICloudStorageView.reloadEncryptedCovers(verifyCode);
            }
        }).show();
    }

    // endregion
}
