import { docPlayerHooks } from '../../../../../documentModel';
import { useCallback, useEffect, useMemo, useRef } from 'react';
// 事件管理器
import { DocPlayerEvts } from '../../../../../pages/docASR/components/businessCommon/DocMediaPlayer';
import evtBus from '../../../../../utils/bus';

const PROGRESS_RECORD_INTERVAL = 6_000; // 播放记录进度显示时间 ms

const usePlayerProgressRecordEffect = () => {
  const { docPlayerData, updatePlayerStatus } =
    docPlayerHooks.useDocPlayerData();
  const { playerRecordTime, playerRecordTimeTipOpen, playerIsPlaying } =
    docPlayerData || {};
  const ProgressRecordTipTimer = useRef<number | null>(null);

  const cachePlayerIsPlaying = useRef<boolean | undefined>();
  useEffect(() => {
    cachePlayerIsPlaying.current = playerIsPlaying;
  }, [playerIsPlaying]);

  useEffect(() => {
    if (
      typeof playerRecordTime === 'number' &&
      Math.round(playerRecordTime / 1000) > 0 &&
      !cachePlayerIsPlaying.current
    ) {
      updatePlayerStatus({
        playerRecordTimeTipOpen: true,
      });
    }
  }, [playerRecordTime, updatePlayerStatus]);

  useEffect(() => {
    if (playerRecordTimeTipOpen && playerIsPlaying) {
      updatePlayerStatus({
        playerRecordTimeTipOpen: false,
      });
    }
  }, [playerIsPlaying, playerRecordTimeTipOpen, updatePlayerStatus]);

  const finalTime = useMemo(() => {
    return playerRecordTime;
  }, [playerRecordTime]);

  // *** 1 监听历史播放记录变更设置播放器进度至指定时间 ***
  useEffect(() => {
    if (typeof finalTime !== 'number') return;
    const normalizedTime = Math.max(finalTime, 0);

    // 纪要页音频播放器历史播放进度同步
    evtBus.emit(DocPlayerEvts.PLAYER_TO_TIME, normalizedTime);
  }, [playerRecordTime, finalTime]);

  const clearProgressRecordTipTimer = useCallback(() => {
    if (!ProgressRecordTipTimer.current) return;
    window.clearTimeout(ProgressRecordTipTimer.current);
    ProgressRecordTipTimer.current = null;
  }, []);

  // *** 2 监听历史播放进度提示显示6S 后关闭提示 ***
  useEffect(() => {
    clearProgressRecordTipTimer();
    if (!playerRecordTimeTipOpen) return;
    ProgressRecordTipTimer.current = window.setTimeout(() => {
      updatePlayerStatus({
        playerRecordTimeTipOpen: false,
      });
    }, PROGRESS_RECORD_INTERVAL);
    return () => {
      clearProgressRecordTipTimer();
    };
  }, [
    clearProgressRecordTipTimer,
    playerRecordTime,
    playerRecordTimeTipOpen,
    updatePlayerStatus,
  ]);
};

export { usePlayerProgressRecordEffect };
