package com.videogo.ui.realplay.helper;

import android.view.View;

import com.videogo.ui.realplay.EZRealPlayActivity;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 定时器管理Helper
 * 播放成功后启动定时器，一秒刷新一次：
 * 1. 计时5秒后自动隐藏横屏TitleBar/控制栏
 * 2. 录像录制计时
 * 3. 刷新码流信息/录像时长UI
 */
public class UpdateTimerHelper {

    private final EZRealPlayActivity mActivity;

    private Timer mUpdateTimer;
    private TimerTask mUpdateTimerTask;

    public UpdateTimerHelper(EZRealPlayActivity activity) {
        mActivity = activity;
    }

    /**
     * 播放成功后，启动定时器，一秒刷新一次
     */
    public void startUpdateTimer() {
        stopUpdateTimer();
        mUpdateTimer = new Timer();
        mUpdateTimerTask = new TimerTask() {
            @Override
            public void run() {
                // 1.计时5秒
                if (mActivity.mLandscapeTitleBar != null && mActivity.mRealPlayControlRl != null
                        && (mActivity.mLandscapeTitleBar.getVisibility() == View.VISIBLE || mActivity.mRealPlayControlRl.getVisibility() == View.VISIBLE)
                        && mActivity.mControlDisplaySec < 5) {
                    mActivity.mControlDisplaySec++;
                }
                // 2.录像录制计时
                if (mActivity.mEZPlayer != null && mActivity.mCaptureRecordHelper.isRecording()) {
                    mActivity.mCaptureRecordHelper.incrementRecordSecond();
                }
                if (mActivity.mHandler != null) {
                    mActivity.mHandler.post(() -> updateRealPlayUI());
                }
            }
        };
        mUpdateTimer.schedule(mUpdateTimerTask, 0, 1000);
    }

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

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

    /**
     * 更新预览UI（横屏导航栏隐藏 & 流量使用 & 录制时长）
     */
    private void updateRealPlayUI() {
        // 倒计时5秒，横屏时隐藏导航栏
        if (mActivity.mControlDisplaySec == 5) {
            mActivity.mControlDisplaySec = 0;
            mActivity.mTitleBarHelper.hideLandscapeTitleBar(false);
        }
        mActivity.mStreamInfoHelper.updateStreamFlow();// 流量使用
        mActivity.mStreamInfoHelper.showStreamFetchType();// 取流方式
        if (mActivity.mCaptureRecordHelper.isRecording()) {// 录像过程中计时UI更新
            mActivity.mCaptureRecordHelper.updateRecordTime();
        }
    }
}
