/**
 * 定时器管理 Helper
 * 从 EZPlayBackListActivity 拆分出来，负责回放进度定时刷新、OSD 时间追踪切片切换等逻辑
 */
package com.videogo.ui.playback.helper;

import com.videogo.openapi.bean.resp.CloudPartInfoFile;
import com.videogo.ui.common.EZBusinessTool;
import com.videogo.ui.playback.EZPlayBackListActivity;
import com.videogo.ui.playback.RemoteListContant;
import com.videogo.ui.playback.RemoteListUtil;
import com.videogo.ui.playback.bean.ClickedListItem;
import com.videogo.ui.playback.querylist.RecordRecyclerAdapter;
import com.videogo.util.DateTimeUtil;
import com.videogo.util.LogUtil;

import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 定时器管理 Helper
 * 管理回放进度定时器（每秒刷新进度条 + OSD 时间追踪）
 * <p>
 * 直接持有 Activity 引用，生命周期与 Activity 一致
 */
public class UpdateTimerHelper {

    private static final String TAG = "UpdateTimerHelper";

    private final EZPlayBackListActivity mActivity;// Activity 引用
    private Timer mUpdateTimer = null;// 播放定时器，每秒刷新
    private TimerTask mUpdateTimerTask = null;// 定时器执行的任务

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

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

    /**
     * 回放进度 UI每秒刷新
     * Playback progress UI refreshes every second
     */
    public void playBoxToolRefresh() {
        // 已播放时长 & 播放进度更新
        if (mActivity.mPlaybackPlayer != null && mActivity.mStatus == RemoteListContant.STATUS_PLAYING) {
            Calendar osdTime = mActivity.mPlaybackPlayer.getOSDTime();
            if (osdTime != null) {
                long osd = osdTime.getTimeInMillis();
                // 根据 OSD 时间刷新录像选中状态：如果当前时间超出了当前片段范围，查找对应片段并更新
                updateSelectedRecordByOSD(osd);
                // 获取当前片段的时间范围
                long begin = mActivity.currentClickItemFile.getBeginTime();
                long end = mActivity.currentClickItemFile.getEndTime();

                double x = ((osd - begin) * RemoteListContant.PROGRESS_MAX_VALUE) / (double) (end - begin);
                int progress = (int) x;
                mActivity.progressSeekbar.setProgress(progress);

                LogUtil.i(TAG,
                        "handlePlayProgress, begin time:" + DateTimeUtil.formatTimeToYMDHMSString(begin) +
                                " endtime:" + DateTimeUtil.formatTimeToYMDHMSString(end) +
                                " osdTime:" + DateTimeUtil.formatTimeToYMDHMSString(osd) +
                                " progress:" + progress + " maxProgress:" + RemoteListContant.PROGRESS_MAX_VALUE);
                if (osd >= begin && osd <= end) {
                    int beginTimeClock = (int) ((osd - begin) / 1000);
                    mActivity.playTimeTV.setText(RemoteListUtil.convToUIDuration(beginTimeClock));
                }
            }
        }
    }

    /**
     * 开启定时器，回放进度 UI 每秒刷新
     */
    public void startUpdateTimer() {
        stopUpdateTimer();
        mUpdateTimer = new Timer();
        mUpdateTimerTask = new TimerTask() {
            @Override
            public void run() {
                mActivity.mHandler.post(() -> playBoxToolRefresh());
            }
        };
        mUpdateTimer.schedule(mUpdateTimerTask, 0, 1000);
    }

    /**
     * 停止定时器
     */
    public void stopUpdateTimer() {
        // 停止录像计时
        if (mUpdateTimer != null) {
            mUpdateTimer.cancel();
            mUpdateTimer = null;
        }

        if (mUpdateTimerTask != null) {
            mUpdateTimerTask.cancel();
            mUpdateTimerTask = null;
        }
    }

    // endregion

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

    /**
     * 根据 OSD 时间戳更新录像列表的选中状态
     * 当连续回放跨越片段时，自动切换到对应的录像片段
     */
    private void updateSelectedRecordByOSD(long osdMillis) {
        RecordRecyclerAdapter adapter = mActivity.mRecordQueryHelper.getCurrentAdapter();
        if (adapter == null) return;
        List<CloudPartInfoFile> dataList = adapter.getData();
        if (dataList == null || dataList.isEmpty()) return;

        long currentBegin = mActivity.currentClickItemFile.getBeginTime();
        long currentEnd = mActivity.currentClickItemFile.getEndTime();
        // 如果 OSD 时间仍在当前片段范围内，不需要切换
        if (osdMillis >= currentBegin && osdMillis <= currentEnd) return;

        // 查找 OSD 时间所属的录像片段
        int index = EZBusinessTool.findRecordIndexByTime(dataList, osdMillis);
        if (index >= 0) {
            CloudPartInfoFile file = dataList.get(index);
            long fileStart = file.getStartMillis();
            long fileEnd = file.getEndMillis();
            mActivity.currentClickItemFile = new ClickedListItem(
                    file.getPosition(), mActivity.mRecordType, fileStart, fileEnd, index);
            mActivity.currentClickItemFile.setFileSize(file.getFileSize());
            mActivity.setPlaybackProgressUI(fileStart, fileEnd);
            adapter.setSelectedPosition(index);
            // 同步更新下载用的录像信息对象，避免连续播放切片后下载的仍是上一个片段
            mActivity.updateRecordInfoByCloudPartFile(file);
        }
    }

    // endregion
}
