import { useCallback, useRef } from 'react';

// 数据
import { docPlayerHooks } from '../../../../../documentModel';

import * as ParagraphsEvts from '../../../../../pages/docASR/utils/constants';
import evtBus from '../../../../../utils/bus';

// 音视频共享状态切换逻辑
export const usePlayerStateChange = () => {
  const { docPlayerData, updatePlayerStatus } =
    docPlayerHooks.useDocPlayerData();
  const { playerRecordTime } = docPlayerData || {};

  /** 内部播放器状态 */
  // 内部状态引用
  interface iPlayerStatus {
    playerMode?: 'video' | 'audio'; // 播放器模式
    // 播放器基础状态
    playerCurtTime?: number; // 当前播放时间
    playerMuted?: boolean; // 播放器是否静音
    playerVolume?: number; // 播放器是否显示音量
    playerRate?: number; // 播放速率
    // 播放器业务状态
    skipBlankSegment?: boolean; // 是否跳过空白片段
  }
  const playerRefState = useRef<iPlayerStatus>({});
  // 更新播放状态
  const updateVideoPlayerStatus = useCallback(
    (status: iPlayerStatus) => {
      playerRefState.current = {
        ...playerRefState.current,
        ...status,
      };
      updatePlayerStatus(status);
      // TODO: 埋点
    },
    [updatePlayerStatus],
  );

  /** 视频状态监听 */
  // 播放器音量变化
  const onPlayerVolumeChange = useCallback(
    (volume: number, muted: boolean) => {
      // 更新状态
      updateVideoPlayerStatus({
        playerVolume: volume,
        playerMuted: muted,
      });
    },
    [updateVideoPlayerStatus],
  );
  // 播放器播放速率变化
  const onPlayerRateChange = useCallback(
    (rate: number) => {
      updateVideoPlayerStatus({
        playerRate: rate,
      });
    },
    [updateVideoPlayerStatus],
  );
  // 跳过空白片段发生变化
  const onPlayerSkipBlankChange = useCallback(
    (skipBlankSegment: boolean) => {
      updateVideoPlayerStatus({
        skipBlankSegment,
      });
    },
    [updateVideoPlayerStatus],
  );

  /** 播放器操作 */
  // 播放器时间更新后，触发音字回显展示
  const onPlayerTimeUpdateToDisplayText = useCallback(
    (curtTime: number) => {
      const normalizedCurtTime = Math.round(curtTime);
      const saveCurtTime = playerRefState.current.playerCurtTime; // 当前保存的时间

      // 时间不同步时候需要进行同步
      if (saveCurtTime !== curtTime) {
        // 音字对照功能同步，其他地方有监听此事件(历史进度记录更新不触发此事件)
        //  *** step1:无历史播放进度
        if (curtTime && !playerRecordTime) {
          evtBus.emit(ParagraphsEvts.CURRENTTIME_TINGWU2, curtTime, false);
        }
        // *** step2:有历史播放进度记录 且 与最近时间不同
        if (
          curtTime &&
          playerRecordTime &&
          playerRecordTime !== normalizedCurtTime
        ) {
          evtBus.emit(ParagraphsEvts.CURRENTTIME_TINGWU2, curtTime, false);
        }
        updateVideoPlayerStatus({ playerCurtTime: curtTime }); // 保存时间
      }
    },
    [playerRecordTime, updateVideoPlayerStatus],
  );

  return {
    onPlayerVolumeChange,
    onPlayerRateChange,
    onPlayerSkipBlankChange,
    onPlayerTimeUpdateToDisplayText,
  };
};
